[英]Multiple 2D histogram on same plot
I have this script to extract data from an image and roi.我有这个脚本来从图像和 roi 中提取数据。 I have everything working perfectly except the end when I output the graphs.
除了输出图形的最后之外,我的所有工作都完美无缺。 Basically I'm having trouble with the windowing of both histograms.
基本上我在两个直方图的窗口化方面都遇到了问题。 It doesn't matter if I change the gridsize, mincount, figure size, or x and y limits one of the histograms will always be slightly stretched.
如果我更改网格大小、最小计数、图形大小或 x 和 y 限制,其中一个直方图将始终略微拉伸,这无关紧要。 When I plot them individually they aren't stretched.
当我单独绘制它们时,它们不会被拉伸。 Is there a way to make the hexagons on the same plot a consistent "non-stretched" shape?
有没有办法使同一个图上的六边形成为一致的“非拉伸”形状? Down below is my graph and plotting methods.
下面是我的图表和绘图方法。 (I left out my data extraction methods because it was quite specialized).
(我省略了我的数据提取方法,因为它非常专业)。
plt.ion()
plt.figure(figsize=(16,8))
plt.title('2D Histogram of Entorhinal Cortex ROIs')
plt.xlabel(x_inputs)
plt.ylabel(y_inputs)
colors = ['Reds','Blues']
x = []
y= []
#image extraction code
hist1 = plt.hexbin(x[0],y[0], gridsize=100,cmap='Reds',mincnt=10, alpha=0.35)
hist2 = plt.hexbin(x[1],y[1], gridsize=100,cmap='Blues',mincnt=10, alpha=0.35)
plt.colorbar(hist1, orientation="vertical")
plt.colorbar(hist2, orientation="vertical")
plt.ioff()
plt.show()
This issue can be solved by setting limits for the bins with the extent
parameter.这个问题可以通过使用
extent
参数设置 bin 的限制来解决。 This can be done automatically by computing the minimum and maximum x and y values across all the data being plotted.这可以通过计算所有绘制数据的最小和最大 x 和 y 值来自动完成。 In cases where
gridsize
is small (eg 10), this approach may result in some of the bins being partially outside of the plot limits.在
gridsize
很小(例如 10)的情况下,这种方法可能会导致某些 bin 部分超出绘图限制。 If so, setting a margin with plt.margins
can help display all the bins within the plot.如果是这样,使用
plt.margins
设置边距可以帮助显示图中的所有 bin。
import numpy as np # v 1.20.2
import matplotlib.pyplot as plt # v 3.3.4
# Create a random dataset
rng = np.random.default_rng(seed=123) # random number generator
size = 10000
x1 = rng.normal(loc=5, scale=10, size=size)
y1 = rng.normal(loc=5, scale=2, size=size)
x2 = rng.normal(loc=-30, scale=5, size=size)
y2 = rng.normal(loc=-20, scale=5, size=size)
# Define hexbin grid extent
xmin = min(*x1, *x2)
xmax = max(*x1, *x2)
ymin = min(*y1, *y2)
ymax = max(*y1, *y2)
ext = (xmin, xmax, ymin, ymax)
# Draw figure with colorbars
plt.figure(figsize=(10, 6))
hist1 = plt.hexbin(x1, y1, gridsize=30, cmap='Reds', mincnt=10, alpha=0.3, extent=ext)
hist2 = plt.hexbin(x2, y2, gridsize=30, cmap='Blues', mincnt=10, alpha=0.3, extent=ext)
plt.colorbar(hist1, orientation='vertical')
plt.colorbar(hist2, orientation='vertical')
# plt.margins(0.1) # Uncomment this if hex bins are partially outside of plot limits
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.