Custom binning in seaborn pairplot

有些话、适合烂在心里 提交于 2020-01-06 06:31:07

问题


I am new to seaborn, and I'm currently playing around with the pairplot functionalities... With the following

seaborn.pairplot(data,
                 hue="Class",
                 diag_king="hist",
                 diag_kws={'alpha'=0.5}
                 )

I'm able to achieve most of what I want: a grid of scatter plots from my pandas dataframe data, with separated distributions according to the Class column, and semi-transparent histograms along the diagonal.

I've figured out that by passing bin=[...] to diag_kws I can have all diagonal plots adopt that binning, but I'd like each column of my dataframe to take its binning from a dedicated dictionary (with keys the column names).

Is it possible to achieve this with diag_kws? Or do I need to access each of the diagonal plots individually after calling pairplot and rebin them manually? What's the most efficient way?


回答1:


PairGrid offers map_diag which one could use to map a custom function which changes the parameters in each call. This could look like this. Mind that one needs to take care of the order (via vars argument) to make sure the correct parameters are applied.

import matplotlib.pyplot as plt
import seaborn as sns


iris = sns.load_dataset("iris", cache=True)
col_list = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width'] 
cols = iter(col_list)

bins = {'sepal_length' : 10, 'sepal_width' : 5, 
        'petal_length' : 35, 'petal_width' : 12}


def myhist(x, **kwargs):
    b = bins[next(cols)]
    plt.text(0.5,0.9, f"bins = {b}", ha="center", 
             transform=plt.gca().transAxes)
    plt.hist(x, bins=b, **kwargs)


g = sns.PairGrid(iris, vars=col_list)
g = g.map_diag(myhist)
g = g.map_offdiag(plt.scatter)

plt.show()



来源:https://stackoverflow.com/questions/56384137/custom-binning-in-seaborn-pairplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!