【问题标题】:How to get hexagon in matplotlib.hexbin flat side up如何在 matplotlib.hexbin 中获得六边形平面朝上
【发布时间】:2021-11-14 06:22:47
【问题描述】:

考虑这个简单的例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(1000)*2-1
y = np.random.rand(1000)*2-1

plt.hexbin(x,y,gridsize=10)
plt.show()

这将产生以下情节:

该图中的六边形的尖边朝上,即沿 y 方向。有什么办法可以将六边形旋转 90 度,使平面朝上?

【问题讨论】:

    标签: python matplotlib hexagonal-tiles


    【解决方案1】:

    hexbin 表示为PolyCollection。在该集合上调用 get_paths() 会给出基本形式(六边形)的路径。您可以通过替换其顶点来更改该六边形的形式,例如,交换它们的 x 和 y 坐标。这会旋转六边形,但只是近似于每个六边形的计数。

    为了得到更精确的结果,可以通过交换 x 和 y 来计算 hexbins,然后还交换六边形网格位置。

    下面是一些示例代码:

    import numpy as np
    from matplotlib import pyplot as plt
    
    x = 2 + np.random.rand(200) * 2
    y = np.random.rand(200) * 2
    
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 4))
    
    hexb = ax1.hexbin(x, y, gridsize=10, cmap='Reds')
    ax1.scatter(x, y, color='blue', alpha=0.5)
    for (xi, yi), val in zip(hexb.get_offsets(), hexb.get_array()):
        if val > 0:
            ax1.text(xi, yi, f'{val:.0f}', color='lime', ha='center', va='center')
    
    hexb = ax2.hexbin(y, x, gridsize=10, cmap='Reds')  # exchange x and y
    xlim = ax2.get_xlim()
    ylim = ax2.get_ylim()
    hexagon = hexb.get_paths()[0]
    hexagon.vertices = hexagon.vertices[:, ::-1]  # exchange the x and y coordinates of the basic hexagon
    offsets = hexb.get_offsets()
    hexb.set_offsets(offsets[:, ::-1])
    ax2.scatter(x, y, color='blue', alpha=0.5)
    ax2.set_ylim(xlim)  # apply the original ylim to xlim
    ax2.set_xlim(ylim)
    for (xi, yi), val in zip(hexb.get_offsets(), hexb.get_array()):
        if val > 0:
            ax2.text(xi, yi, f'{val:.0f}', color='lime', ha='center', va='center')
    plt.show()
    

    【讨论】:

    • 谢谢。但是,这只是视觉旋转还是六边形在此过程中实际上会改变颜色?由于旋转六边形覆盖的区域与原始六边形不同
    • 我更新了代码,计算了交换了 x 和 y 的 hexbins 并可视化了计数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多