Building a 2nd histogram with a total value, not a score

Novice user on the forum. Please help me. I have a data set: x, y coordinates, each x, y has a value. I want to build a two-dimensional histogram that displays the sum of the values ​​in each bin with a color scale. matplotlib hexbin is straightforward. I can do it. eg:

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

However, I am struggling to make a similar plot with histogram2d or matplotlib hist2d. I think I need to somehow combine binned_statistic_2d and histogram2d. No problem if I replaced the line plt.hexbin above:

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

Any clue? I look at the forum, but I can not find the working code.

0
source share
1 answer

, , imshow.

pandas, (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

0

Source: https://habr.com/ru/post/1684050/


All Articles