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