Stacked barchart in PairGrid python seaborn

后端 未结 1 942
不思量自难忘°
不思量自难忘° 2021-01-25 15:52

I whish to reproduce the PairGrid plot found in that tutorial, but locally my barcharts are not stacked as in the tutorial and I can\'t figure out how to make them so.

相关标签:
1条回答
  • 2021-01-25 16:42

    The option for stacked histograms on the diagonal of a PairGrid has been removed from seaborn in this commit and hence is not available anymore in seaborn 0.9.

    A workaround could be to collect all the data first and then plot it to the respective axes.

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd 
    
    df = sns.load_dataset('mpg')
    
    g = sns.PairGrid(data=df[["mpg", "horsepower", "weight", "origin"]], hue="origin")
    g.map_upper(sns.regplot)
    g.map_lower(sns.residplot)
    
    # below for the histograms on the diagonal
    d = {}
    def func(x, **kwargs):
        ax = plt.gca()
    
        if not ax in d.keys():
            d[ax] = {"data" : [], "color" : []}
        d[ax]["data"].append(x)
        d[ax]["color"].append(kwargs.get("color"))
    
    g.map_diag(func)
    for ax, dic in d.items():
        ax.hist(dic["data"], color=dic["color"], histtype="barstacked")
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题