带有 2D 函数的 Python hexbin 图

问题描述 投票:0回答:1

我尝试使用 pyplot.hexbin 在六角形网格上显示二维函数,但它只生成一条线并忽略函数的其余部分。我该如何解决这个问题?

def func(x,y):
    return x*2+y*2

x = np.linspace((-0.5)/4*5, (0.5)/4*5, int(2e3))   
y = np.linspace(-0.5, 0.5, int(2e3))    

plt.hexbin(x,
           y,
           func(x,y), 
           gridsize=(8,4),
           cmap='gnuplot')
plt.show()

在此输入图片描述

python matplotlib
1个回答
0
投票

func(x,y) 函数为每个 (x, y) 对返回一个标量值,但 hexbin 期望 x 和 y 是表示坐标的相同长度的数组。输入另一个带有标量值的数组 Z,该标量值将是每个十六进制的颜色。 尝试:

import numpy as np
import matplotlib.pyplot as plt

def func(x,y):
    return x*2+y*2

x = np.linspace((-0.5) / 4 * 5, (0.5) / 4 * 5, int(2e3))
y = np.linspace(-0.5, 0.5, int(2e3))
X, Y = np.meshgrid(x, y)

# Evaluate the function for each combination of x and y
Z = func(X, Y)

plt.hexbin(X.flatten(),    # Flatten X and Y to 1D arrays
           Y.flatten(),
           C=Z.flatten(),  # Flatten Z to 1D array for color values
           gridsize=(8, 4),
           cmap='gnuplot')

plt.show()

您还可以在演出前添加颜色条,例如:

plt.colorbar(label='Function Value')
© www.soinside.com 2019 - 2024. All rights reserved.