二维直方图,其中一个轴是累积的,另一个不是

问题描述

假设我有两个可以被视为配对的随机变量的实例。

import numpy as np
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)

使用 matplotlib 可以很容易地制作二维直方图。

import matplotlib.pyplot as plt
plt.hist2d(x,y)

在 1D 中,matplotlib 有一个选项可以使直方图累积。

plt.hist(x,cumulative=True)

我想要的是包含两个类的元素。我想构建一个二维直方图,使横轴是累积的,而纵轴不是累积的。

有没有办法用 Python/Matplotlib 做到这一点?

解决方法

您可以利用 np.cumsum 创建累积直方图。首先保存 hist2d 的输出,然后在绘图时应用于您的数据。

import matplotlib.pyplot as plt
import numpy as np

#Some random data
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)

#create a figure
plt.figure(figsize=(16,8))

ax1 = plt.subplot(121) #Left plot original
ax2 = plt.subplot(122) #right plot the cumulative distribution along axis

#What you have so far
ax1.hist2d(x,y)

#save the data and bins
h,xedge,yedge,image = plt.hist2d(x,y)

#Plot using np.cumsum which does a cumulative sum along a specified axis
ax2.pcolormesh(xedge,np.cumsum(h.T,axis=1))

plt.show()

enter image description here