<p>在创建第二个图例之前,您需要保存对第一个图例的引用,并将其作为单独的艺术家添加到<code>ax</code>。这样,对<code>ax.legend(...)</code>的第二次调用不会删除第一个图例</p>
<p>对于第二个图例,我只是为每种独特的颜色创建了一个圆圈,并将其添加到中。我忘了怎么画真正的圆,所以我用了<code>Line2D</code>和<code>lw=0, marker="o"</code>来画圆</p>
<p>使用图例的<code>bbox_to_anchor</code>和<code>loc</code>关键字来获得令您满意的结果</p>
<p>我摆脱了依赖<code>plt.<something></code>的一切,因为这是忘记哪个方法附加到哪个对象的最好方法。现在一切都在<code>ax.<something></code>或<code>fig.<something></code>中。当您有多个轴时,或者当您想将画布嵌入PyQt应用程序时,这也是正确的方法<code>plt</code>不会做你期望的事情</p>
<p>最初的代码是由<em>@r-初学者</em>提供的,我只是在此基础上构建的</p>
<pre><code># Imports.
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np
# Figure.
figure = plt.figure(figsize=(12, 10))
ax = figure.add_subplot(projection="3d")
ax.set_xlabel("PC1: Type")
ax.set_ylabel("PC2: Length")
ax.set_zlabel("PC3: Frequency")
ax.set_title("scatter 3D legend")
# Data and 3D scatter.
colors = ["red", "blue", "yellow", "black", "pink", "purple", "orange", "black", "red" ,"blue"]
df = pd.DataFrame({"type": np.random.randint(0, 5, 10),
"length": np.random.randint(0, 20, 10),
"freq": np.random.randint(0, 10, 10),
"size": np.random.randint(20, 200, 10),
"colors": np.random.choice(colors, 10)})
sc = ax.scatter(df.type, df.length, df.freq, alpha=0.6, c=colors, s=df["size"], marker="o")
# Legend 1.
handles, labels = sc.legend_elements(prop="sizes", alpha=0.6)
legend1 = ax.legend(handles, labels, bbox_to_anchor=(1, 1), loc="upper right", title="Sizes")
ax.add_artist(legend1) # <- this is important.
# Legend 2.
unique_colors = set(colors)
handles = []
labels = []
for n, color in enumerate(unique_colors, start=1):
artist = mpl.lines.Line2D([], [], color=color, lw=0, marker="o")
handles.append(artist)
labels.append(str(n))
legend2 = ax.legend(handles, labels, bbox_to_anchor=(0.05, 0.05), loc="lower left", title="Classes")
figure.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/zPRjc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zPRjc.png" alt="enter image description here"/></a></p>
<p>与问题无关:<a href="https://stackoverflow.com/a/14860958/9282844">because of how markersize works for circles</a>,可以使用<code>s = df["size"]**2</code>而不是<code>s = df["size"]</code></p>