创建相关的matplotlib散点图例大小 [英] creating a matplotlib scatter legend size related

查看:157
本文介绍了创建相关的matplotlib散点图例大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种包含(matplotlib)图例的方法,该图例描述散点图中的点的大小,因为这可能与另一个变量相关,例如在此基本示例中:

I am looking for a way to include a (matplotlib) legend that describe the size of points in a scatter plot, as this could be related to another variable, like in this basic example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
a2 = 400*np.random.rand(N)

plt.scatter(x, y, s=a2, alpha=0.5)
plt.show()

(灵感来自: http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html )

因此,根据scatter中的s描述符,在图例中理想情况下,对应于0-400大小(a2变量)的斑点很少.

so in the legend there would be ideally few spots corresponding to sizes 0-400 (the a2 variable), according to s descriptor in scatter.

推荐答案

下面的解决方案使用pandas将大小分组到集合容器中(使用这个问题中的合并配方.

The solution below used pandas to group the sizes together into set bins (with groupby). It plots each group and assigns it a label and a size for the markers. I have used the binning recipe from this question.

注意,这与您所陈述的问题略有不同,因为标记大小被合并,这意味着a2中的两个元素(例如36和38)将具有与它们内部相同的大小相同的装箱.您可以随时增加垃圾箱的数量,以使其更适合自己.

Note this is slightly different to your stated problem as the marker sizes are binned, this means that two elements in a2, say 36 and 38, will have the same size as they are within the same binning. You can always increase the number of bins to make it finer as suits you.

使用此方法,您可以为每个垃圾箱更改其他参数,例如标记的形状或颜色.

Using this method you could vary other parameters for each bin, such as the marker shape or colour.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

N = 50
M = 5 # Number of bins

x = np.random.rand(N)
y = np.random.rand(N)
a2 = 400*np.random.rand(N)

# Create the DataFrame from your randomised data and bin it using groupby.
df = pd.DataFrame(data=dict(x=x, y=y, a2=a2))
bins = np.linspace(df.a2.min(), df.a2.max(), M)
grouped = df.groupby(np.digitize(df.a2, bins))

# Create some sizes and some labels.
sizes = [50*(i+1.) for i in range(M)]
labels = ['Tiny', 'Small', 'Medium', 'Large', 'Huge']

for i, (name, group) in enumerate(grouped):
    plt.scatter(group.x, group.y, s=sizes[i], alpha=0.5, label=labels[i])

plt.legend()
plt.show()

这篇关于创建相关的matplotlib散点图例大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆