請看這個簡單的例子:
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度,使其平坦的一面朝上?
uj5u.com熱心網友回復:
六邊形被表示為一個PolyCollection。 在該集合上呼叫get_paths()可以得到基本形式(一個六角形)的路徑。你可以通過替換其頂點來改變該六邊形的形式,例如,交換其x和y坐標。這將旋轉六邊形,但對于進入每個六邊形的計數來說只是近似的。
為了得到更精確的結果,可以在交換了x和y的情況下計算六邊形,然后再交換六邊形的網格位置。
下面是一些示例代碼:
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') #交換x和y
xlim = ax2.get_xlim()
ylim = ax2.get_ylim()
hexagon = hexb.get_paths()[0]
hexagon.vertices = hexagon.vertices[:, ::-1] # 交換基本六邊形的x和y坐標。
offsets = hexb.get_offsets()
hexb.set_offsets(offsets[:, ::-1] )
ax2.scatter(x, y, color='blue', alpha=0.5)
ax2.set_ylim(xlim) # 將原來的ylim應用于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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/328924.html
標籤:


