代码之家  ›  专栏  ›  技术社区  ›  Luis Ramon Ramirez Rodriguez

绘图加权直方图

  •  5
  • Luis Ramon Ramirez Rodriguez  · 技术社区  · 7 年前

    matplotlib plotly ,但似乎 没有很好的集成 pandas

    sns.distplot(df.X, bins=25, hist_kws={'weights':df.W.values},norm_hist=False,kde=False)  
    

    但是我没有找到一个简单的方法来解决这个问题 阴谋地 pandas.DataFrame 使用 以直截了当的方式?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Jwely    7 年前

    plotly 直方图对象似乎不支持权重。然而 numpys 直方图函数支持权重,并且可以轻松地计算从绘图条形图创建直方图所需的一切。

    # dataframe with bimodal distribution to clearly see weight differences.
    import pandas as pd
    from numpy.random import normal
    import numpy as np
    
    df =pd.DataFrame(
        {"X": np.concatenate((normal(5, 1, 5000), normal(10, 1, 5000))),
         "W": np.array([1] * 5000 + [3] * 5000)
        })
    

    您包含的seaborn call适用于以下数据:

    # weighted histogram with seaborn
    from matplotlib import pyplot as plt
    import seaborn as sns
    
    sns.distplot(df.X, bins=25, 
        hist_kws={'weights':df.W.values}, norm_hist=False,kde=False)
    plt.show()
    

    我们可以看到,我们的任意1和3权重被正确地应用于每种分布模式。

    enter image description here

    Bar 带numpy的图形对象

    # with plotly, presuming you are authenticated
    import plotly.plotly as py
    import plotly.graph_objs as go
    
    # compute weighted histogram with numpy
    counts, bin_edges = np.histogram(df.X, bins=25, weights=df.W.values)
    data = [go.Bar(x=bin_edges, y=counts)]
    
    py.plot(data, filename='bar-histogram')
    

    您可能需要重新实现直方图的其他注释功能以适应您的用例,这些功能可能会带来更大的挑战,但plotly上的绘图内容本身工作得很好。

    请参见此处的渲染: https://plot.ly/~Jwely/24/#plot