【问题标题】:Python Plotly CDF with Frequency DIstribution DataPython Plotly CDF 与频率分布数据
【发布时间】:2021-03-31 18:41:57
【问题描述】:

如何使用 Plotly 在 Pandas DataFrame 中制作包含频率分布数据的 CDF 图?假设以下玩具数据

value   freq    
1       3
2       2
3       1

所有示例都展示了如何使用如下所示的原始数据进行操作:

value
1
1
1
2
2
3

我可以像这样用 Pandas .plot 做到这一点(但我更愿意用 Plotly 做同样的事情):

stats_df = df
stats_df['pdf'] = stats_df['count'] / sum(stats_df['count'])

# calculate CDF
stats_df['cdf'] = stats_df['pdf'].cumsum()
stats_df = stats_df.reset_index()

# plot
stats_df.plot(x = 'n_calls', 
              y = ['pdf', 'cdf'], 
              logx = True,
              kind = 'line',
              grid = True)

如果您想使用玩具数据集进行演示,这里有一个:https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv

参考资料:

https://plotly.com/python/v3/discrete-frequency/

https://plotly.com/python/distplot/

【问题讨论】:

    标签: python plotly data-visualization plotly-python


    【解决方案1】:

    无法在 Plotly 中构建 CDF。

    在 Plotly 上,只能绘制 PDF 和直方图(酒精样本见下文)。

    上图的代码如下所示:

    import plotly.figure_factory as ff
    import pandas as pd
    
    data = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv')
    
    x = data['alcohol'].values.tolist()
    
    group_labels = ['']
    fig = ff.create_distplot([x], group_labels,
                             bin_size=.25, show_rug=False)
    fig.show()
    
    

    如果您确实需要 CDF,请使用第三方库进行数据准备。 在下面的示例中,我使用的是 Numpy。

    上图的代码如下所示:

    import plotly.graph_objs as go
    import numpy as np
    import pandas as pd
    
    data = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv')
    
    x = data['alcohol'].values.tolist()
    
    hist, bin_edges = np.histogram(x, bins=100, density=True)
    cdf = np.cumsum(hist * np.diff(bin_edges))
    fig = go.Figure(data=[
        go.Bar(x=bin_edges, y=hist, name='Histogram'),
        go.Scatter(x=bin_edges, y=cdf, name='CDF')
    ])
    fig.show()
    

    请注意,CDF 是虚线。这是因为这不是未知分布的近似函数。 要得到一个平滑的函数,你需要知道分布规律。

    【讨论】:

      猜你喜欢
      • 2015-11-09
      • 2013-03-19
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2014-07-08
      • 2012-04-19
      • 2011-08-20
      • 1970-01-01
      相关资源
      最近更新 更多