gpt4 book ai didi

python - 在Python中用梯度求和重叠的气泡

转载 作者:行者123 更新时间:2023-12-02 08:08:48 25 4
gpt4 key购买 nike

我想绘制一张特定地点的 map ,以解释它们对周围城市环境的影响。为此,我想将站点绘制为气泡,朝向圆的边缘逐渐减小梯度,并且重叠圆的梯度是总和。

作为一个例子,我使用了这个:

# libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

# create data
x = np.random.rand(15)
y = x+np.random.rand(15)
z = x+np.random.rand(15)
z=z*z

# Change color with c and alpha. I map the color to the X axis value.
plt.scatter(x, y, s=1500, c=z, cmap="Blues", alpha=0.4, edgecolors="grey", linewidth=1)

# Add titles (main and on axis)
plt.xlabel("the X axis")
plt.ylabel("the Y axis")
plt.title("A colored bubble plot")

plt.show();

产生:

enter image description here

但是,圆圈​​的颜色并没有衰减,它们似乎也没有按照预期的方式求和。

是否有任何聪明的方法可以做到这一点,或者使用某种热图解决方案可能会更容易,或者使用网格和相邻图 block 的衰减效果?

最佳答案

这是一种在每个 x 和 y 处放置密度并按 z 值放大的方法。根据到每个 x,y 位置的距离添加数量。

import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import norm # calculate the length of a vector
# import seaborn as sns

# create data
x = np.random.rand(15)
y = x+np.random.rand(15)
z = x+np.random.rand(15)
z=z*z

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12,5))
# Change color with c and alpha. I map the color to the X axis value.
ax1.scatter(x, y, s=1500, c=z, cmap="Blues", alpha=0.4, edgecolors="grey", linewidth=1)
ax1.set_xlabel("the X axis")
ax1.set_ylabel("the Y axis")
ax1.set_title("A colored bubble plot")

centers = np.dstack((x, y))[0]
xmin = min(x)-0.2
xmax = max(x)+0.2
ymin = min(y)-0.2
ymax = max(y)+0.2
zmin = min(z)
zmax = max(z)
xx, yy = np.meshgrid(np.linspace(xmin, xmax, 100),
np.linspace(ymin, ymax, 100))
xy = np.dstack((xx, yy))
zz = np.zeros_like(xx)
for ci, zi in zip(centers, z):
sigma = zi / zmax * 0.3
sigma2 = sigma ** 2
zz += np.exp(- norm(xy - ci, axis=-1) ** 2 / sigma2 / 2)

img = ax2.imshow(zz, extent=[xmin, xmax, ymin, ymax], origin='lower', aspect='auto', cmap='Blues')
#plt.colorbar(img, ax=ax2)

ax2.set_xlabel("the X axis")
ax2.set_ylabel("the Y axis")
ax2.set_title("Density depending on z")

plt.show()

该图使用相同的随机数据比较了两种方法。

sample plot

关于python - 在Python中用梯度求和重叠的气泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60111978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com