python - 在python中将重叠的气泡与梯度相加
问题描述
我想绘制一张特定地点的地图,以解释它们对周围城市环境的影响。为此,我想将站点绘制为气泡,向圆的边缘逐渐减小梯度,重叠圆的梯度是总和。
作为一个例子,我使用了这个:
# 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();
产生:
然而,圆圈的颜色并没有衰减,它们似乎也没有按照预期的方式求和。
有什么聪明的方法可以做到这一点,或者使用某种热图解决方案,或者使用网格和对相邻图块的衰减效果可能会更容易?
解决方案
这是一种将密度放置在每个 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()
该图使用相同的随机数据比较了两种方法。
推荐阅读
- python - Checkgradient没有解决MATLAB中的优化问题
- java - 将数据从 CSV 文件添加到 Java Derby 数据库在关闭窗口后删除
- javascript - 如果存在另一个域中的 mp4 文件,请使用 JavaScript 检查
- javascript - 获取隐藏元素并将其发送到不同的 URL
- algorithm - 这段代码的循环不变量是什么?
- javascript - Add multiple select options to url paramter with Javascript
- java - 如何使用 gson 或 JSONObject 从 json 响应中读取数据?
- esp32 - ESP32 - Preferences.h - 将值存储到内存
- javascript - 使用 express/sequelize 投票向上/向下 1 次
- python - uwsgi 无法从 docker 内部加载烧瓶和芹菜