【问题标题】:Taking the mean of square bins in matplotlib在 matplotlib 中取平方箱的平均值
【发布时间】:2017-11-07 18:58:16
【问题描述】:

我目前有一个散点图,其中包含 3 组数据、一个 x 坐标、一个 y 坐标以及每个 x、y 的值。这些集合是一维 numpy 数组。

matplotlib 中的 matplotlib.axes.Axes.hexbin 函数在每个 bin 内的每个 x,y 处累积所有分配的值,然后取其平均值。这会产生一个带有六边形箱的颜色图。

是否可以使用 matplotlib 或 numpy 做类似的事情,但使用方形箱?

这是当前的十六进制代码:

plt.hexbin(daylim,Llim, C = elim, gridsize = 168,bins = 'log')

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    您可以在绘图之前计算要在分箱二维图中显示的值,然后显示为imshow 图。

    如果您乐于使用 pandas,一种选择是根据剪切 (pandas.cut) x 和 y 数据对 z 数据进行分组。然后应用平均值 (.mean()) 并 unstack 以获得数据透视表。

    df.z.groupby([pd.cut(x, bins=xbins), pd.cut(y, bins=ybins)]) \
                .mean().unstack(fill_value=0)
    

    这是一个完整的例子:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import  matplotlib.colors
    
    x = np.arange(1,8)
    y = np.arange(1,6)
    X,Y = np.meshgrid(x,y)
    
    df = pd.DataFrame({"x":X.flatten(), "y":Y.flatten(), "z":(X*Y).flatten()})
    
    xbins = [0,4,8]
    ybins = [0,3,6]
    hist = df.z.groupby([pd.cut(df.x, bins=xbins), pd.cut(df.y, bins=ybins)]) \
                .mean().unstack(fill_value=0)
    print hist
    im = plt.imshow(hist.values, norm=matplotlib.colors.LogNorm(1,100))
    plt.xticks(range(len(hist.index)), hist.index)
    plt.yticks(range(len(hist.columns)), hist.columns)
    plt.colorbar(im)
    plt.show()
    

    必须手动创建对数范数,并且需要根据分箱标记刻度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-31
      • 2019-03-19
      • 2022-11-03
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多