python - Pyplot 图例/键,但用于比例,就像在 map 上一样

标签 python matplotlib plot scatter-plot

我正在制作一个散点图,其中标记的大小由列表给出,因此每个标记都是不同的。有没有什么方法可以添加一个键,显示“这个尺寸的圆相当于这个值”等等?就像 map 上的按键显示 1 英寸等于 1 英里一样。 如果它很重要,我会在 Jupyter Notebook 中执行此操作,但我认为这并不重要。

编辑:澄清一下,每个数据点都是许多其他数据点的平均值,每个标记的大小对应于计算该平均值的数据点数量。例如,较小的点之一是 50 个数字的中位数,而较大的标记之一是 150 个数字的中位数的数据点。因此,它们对应的数字并不像 map 那样具有物理尺寸。

我已经按照我想要的方式缩放了标记,我想要的是一个图例/键,指示标记大小与其来源值的关系。

最佳答案

据我了解,您希望标记按比例缩放。对于 plt.scatter() 来说这是不可能的,因为它的标记大小始终以像素为单位。一种选择是使用补丁并将其添加到 PatchCollection 中。

这是一个例子

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection 

patches = []
coordinates = [(0,0), (2,0), (5,2), (1,7.6), (6,7), (2,4), (-1,5)]
sizes = 0.9+np.random.rand(len(coordinates),2)*1.99
print sizes

for i, co in enumerate(coordinates):
    rect = mpatches.Rectangle(co, sizes[i,0], sizes[i,1], ec="k")
    patches.append(rect)

fig, ax = plt.subplots(figsize=(6,5))
ax.set_aspect("equal")
colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)

norm_scale = mpatches.Rectangle((7,-1), 2,2,  ec="k", facecolor="b")
ax.add_patch(norm_scale)
ax.set_xlim([-2,10])
ax.set_ylim([-2,10])
ax.set_ylabel("position [meters]")
ax.set_xlabel("position [meters]")
ax.set_title("Tents on a meddow")
ax.text(8,0.9, "2 m", color="w", ha="center", va="top")
ax.text(7.1,0, "2 m", color="w", ha="left", va="center", rotation=90)
plt.show()

给出下面的图,其中深蓝色补丁是显示标准尺寸的关键。

enter image description here

关于python - Pyplot 图例/键,但用于比例,就像在 map 上一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40696804/

相关文章:

python - 从 PayPal 的 Sandbox IPN 获得无效响应

python - Squish、Python、Windows 应用程序自动化

python - python中散点图的最佳拟合直线的代码

matlab - 在 MATLAB 中处理多个绘图

python - mac 无法安装spark

matplotlib - pad_inches=0 和 bbox_inches ="tight"使绘图小于声明的 figsize

Python:如何使用 matplotlib 将图像像素投影到 map 上

python - 导入为 16 位深但意外的 plt.show() 结果的 DNG 原始图片

python - 在 Pandas 上绘制整行

Python:os.path.exists 在 "~/foo"上失败