【问题标题】:plotting 2dhistogram with sum value rather than count用总和值而不是计数绘制二维直方图
【发布时间】:2017-03-09 07:21:22
【问题描述】:

论坛的初学者。请帮忙。我有一个数据集:x,y 坐标,每个 x,y 都有一个值。我想绘制一个 2d 直方图,用色标显示每个 bin 中的值的总和。 matplotlib 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()

但是,我正在努力使用 histogram2d 或 matplotlib hist2d 制作类似的图。我想我必须以某种方式结合 binned_statistic_2d 和 histogram2d 。如果我将上面的 plt.hexbin 行替换为此没有问题:

plt.hist2d(x = xpos, y = ypos, bins = 50, norm = LogNorm())

有什么线索吗?我在论坛上看过,但似乎找不到有效的代码。

【问题讨论】:

  • 这是做什么的:np.random.rand(0,10,0.1)?
  • 没有。我有一个真实的数据集 x,y。我看到错别字了。我会改正的。
  • 只是一个更新。我已经解决了这个问题。我没有使用 hist2d,而是编写了自己的分箱代码。
  • 使用 numpy 进行分箱的可能解决方案:stackoverflow.com/questions/45777934/…

标签: python matplotlib


【解决方案1】:

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

如果您乐于使用 pandas,一种选择是根据切割 (pandas.cut) x 和 y 数据对大量数据进行分组。然后应用 sum (.sum()) 和 unstack 得到一个数据透视表。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2014-07-03
    • 2010-12-28
    • 2021-05-25
    相关资源
    最近更新 更多