用总和值而不是计数绘制2dhistogram

时间:2017-03-09 07:21:23

标签: python matplotlib

论坛上的初学者用户。请帮忙。我有一个数据集:x,y坐标,每个x,y都有一个值。我想绘制一个2d直方图,用颜色标度显示每个bin中值的总和。 matplotlib hexbin是直截了当的。我可以做这个。例如:

shared_ptr<Base>

然而,我正努力用histogram2d或matplotlib hist2d制作类似的情节。我想我必须以某种方式结合binned_statistic_2d和histogram2d。如果我将上面的plt.hexbin行替换为:

,没问题
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm

xpos = np.random.rand(0,10)
ypos = np.random.rand(0,10)
plt.hexbin(x = xpos, y = ypos, C=mass, cmap= plt.cm.jet, gridsize=100, reduce_C_function=sum, bins="log")  
cb = plt.colorbar()
cb.ax.set_ylabel('log (sum value in each bin)')
plt.xlabel('Xpos')
plt.ylabel('Ypos')
plt.show()

有任何线索吗?我在论坛上看,但似乎找不到工作代码。

1 个答案:

答案 0 :(得分:0)

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

如果您乐意使用pandas,一种选择是根据cut(pandas.cut)x和y数据对海量数据进行分组。然后应用总和(.sum())并取消堆栈以获取数据透视表。

df.mass.groupby([pd.cut(df.x, bins=xbins, include_lowest=True), 
                 pd.cut(df.y, bins=ybins, include_lowest=True)]) \
               .sum().unstack(fill_value=0)

这是一个完整的例子:

import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt
import  matplotlib.colors

xpos = np.random.randint(0,10, size=50)
ypos = np.random.randint(0,10, size=50)
mass = np.random.randint(0,75, size=50)

df = pd.DataFrame({"x":xpos, "y":ypos, "mass":mass})

xbins = range(10)
ybins = range(10)
su = df.mass.groupby([pd.cut(df.x, bins=xbins, include_lowest=True), 
                     pd.cut(df.y, bins=ybins, include_lowest=True)]) \
            .sum().unstack(fill_value=0)
print su
im = plt.imshow(su.values, norm=matplotlib.colors.LogNorm(1,300))
plt.xticks(range(len(su.index)), su.index, rotation=90)
plt.yticks(range(len(su.columns)), su.columns)
plt.colorbar(im)
plt.show()

enter image description here