glu*_*uke 12 python matplotlib legend scatter-plot
我正在寻找一种方法来包含描述散点图中点的大小的(matplotlib)图例,因为这可能与另一个变量有关,就像在这个基本示例中一样:
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()
Run Code Online (Sandbox Code Playgroud)
(灵感来自:http: //matplotlib.org/examples/shapes_and_collections/scatter_demo.html)
所以在传说中a2,根据s描述符,理想情况下很少有与0-400(变量)大小相对应的点scatter.
Imp*_*est 12
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)
sc = plt.scatter(x, y, s=a2, alpha=0.5)
plt.legend(*sc.legend_elements("sizes", num=6))
plt.show()
Run Code Online (Sandbox Code Playgroud)
下面的解决方案用于pandas将大小分组到set bins(with groupby)中.它绘制每个组,并为标记分配标签和大小.我已经使用了这个问题的分档配方.
请注意,这与您所述的问题略有不同,因为标记大小是分箱的,这意味着a236和38 中的两个元素将具有与它们在相同分箱中相同的大小.您可以随时增加垃圾箱数量,使其更适合您.
使用此方法,您可以更改每个bin的其他参数,例如标记形状或颜色.
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()
Run Code Online (Sandbox Code Playgroud)

这也可以,我认为它更简单一点:
msizes = np.array([3, 4, 5, 6, 7, 8])
l1, = plt.plot([],[], 'or', markersize=msizes[0])
l2, = plt.plot([],[], 'or', markersize=msizes[1])
l3, = plt.plot([],[], 'or', markersize=msizes[2])
l4, = plt.plot([],[], 'or', markersize=msizes[3])
labels = ['M3', 'M4', 'M5', 'M6']
leg = plt.legend([l1, l2, l3, l4], labels, ncol=1, frameon=True, fontsize=12,
handlelength=2, loc = 8, borderpad = 1.8,
handletextpad=1, title='My Title', scatterpoints = 1)
Run Code Online (Sandbox Code Playgroud)
我几乎喜欢 mjp 的答案,但它并不完全有效,因为 plt.plot 的 'markersize' 参数与 plt.scatter 的 's' 参数的含义不同。使用 plt.plot 你的尺寸会出错。
而是使用:
marker1 = plt.scatter([],[], s=a2.min())
marker2 = plt.scatter([],[], s=a2.max())
legend_markers = [marker1, marker2]
labels = [
str(round(a2.min(),2)),
str(round(a2.max(),2))
]
fig.legend(handles=legend_markers, labels=labels, loc='upper_right',
scatterpoints=1)
Run Code Online (Sandbox Code Playgroud)