seaborn.FacetGrid and seaborn.pairplot
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import warnings
import numpy as np
warnings.filterwarnings('ignore')
sns.set(style="ticks")
FacetGrid
A FacetGrid can be drawn with up to three dimensions: row, col, and hue
有点像R的ggplot
tips = sns.load_dataset("tips")
tips
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | Male | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | Male | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | Female | No | Sun | Dinner | 4 |
… | … | … | … | … | … | … | … |
239 | 29.03 | 5.92 | Male | No | Sat | Dinner | 3 |
240 | 27.18 | 2.00 | Female | Yes | Sat | Dinner | 2 |
241 | 22.67 | 2.00 | Male | Yes | Sat | Dinner | 2 |
242 | 17.82 | 1.75 | Male | No | Sat | Dinner | 2 |
243 | 18.78 | 3.00 | Female | No | Thur | Dinner | 2 |
244 rows × 7 columns
sns.palplot(sns.color_palette("Set2"))

g = sns.FacetGrid(data=tips, col="day",row='time',hue='sex',palette=sns.color_palette("Set2")[2:4])
g.map(sns.scatterplot,"total_bill","tip")
g.add_legend()
<seaborn.axisgrid.FacetGrid at 0x18ef1acba88>

g = sns.FacetGrid(tips, hue="smoker", palette=sns.color_palette("Set2"), height=5)
g.map(sns.kdeplot,"total_bill")
g.add_legend()
<seaborn.axisgrid.FacetGrid at 0x18ef2499e48>

可以添加自定义绘图函数
sns.palplot(sns.light_palette(color=sns.color_palette("Set2")[0]))

g = sns.FacetGrid(tips, hue="time", col="time", height=4)
g.map(sns.scatterplot,"total_bill","tip")
g.add_legend()
<seaborn.axisgrid.FacetGrid at 0x18ef374d7c8>

def hexbin(x, y, color, **kwargs):
cmap = sns.light_palette(color, as_cmap=True)
plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs)#类似于scatter
with sns.axes_style("white"):
g = sns.FacetGrid(tips, hue="time", col="time", height=4)
g.map(hexbin, "total_bill", "tip", extent=[0, 50, 0, 10]);

seaborn.PairGrid
g = sns.PairGrid(iris, hue="species",palette='deep')#sns.pairplot(iris, hue="species",palette='deep')
g.map_diag(sns.kdeplot,shade=True)
g.map_offdiag(sns.scatterplot)
g.add_legend()
<seaborn.axisgrid.PairGrid at 0x18ef8c8e948>

g = sns.PairGrid(iris, vars=["sepal_length", "sepal_width","petal_length"], hue="species",palette="Set2")
g.map_upper(hexbin,alpha=0.8)
g.map_lower(sns.regplot)
g.map_diag(sns.kdeplot, legend=True,shade=True)
<seaborn.axisgrid.PairGrid at 0x18efbe3ca48>

0 Comments