【问题标题】:Multiple 2D histogram on same plot同一图上的多个 2D 直方图
【发布时间】:2021-07-21 07:16:42
【问题描述】:

我有这个脚本可以从图像和 roi 中提取数据。除了输出图表时,我的一切工作都完美无缺。基本上我在两个直方图的窗口化方面都遇到了麻烦。如果我更改网格大小、最小计数、图形大小或 x 和 y 限制,直方图之一将始终略微拉伸,这并不重要。当我单独绘制它们时,它们不会被拉伸。有没有办法让同一个图上的六边形成为一致的“非拉伸”形状? 下面是我的图表和绘图方法。 (我省略了我的数据提取方法,因为它非常专业)。

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

enter image description here

【问题讨论】:

    标签: python matplotlib histogram histogram2d


    【解决方案1】:

    可以通过使用 extent 参数设置 bin 限制来解决此问题。这可以通过计算所有正在绘制的数据的最小和最大 x 和 y 值来自动完成。在 gridsize 很小的情况下(例如 10),这种方法可能会导致某些 bin 部分超出绘图限制。如果是这样,使用plt.margins 设置边距可以帮助显示绘图中的所有箱。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2019-03-30
      • 2014-12-31
      • 2019-03-08
      相关资源
      最近更新 更多