为 3D 绘图自动创建图例

Mar*_*rio 5 python matplotlib legend

我正在尝试更新以下函数以通过图例报告集群信息:

color_names = ["red", "blue", "yellow", "black", "pink", "purple", "orange"]

def plot_3d_transformed_data(df, title, colors="red"):
 
  ax = plt.figure(figsize=(12,10)).gca(projection='3d')
  #fig = plt.figure(figsize=(8, 8))
  #ax = fig.add_subplot(111, projection='3d')
  

  if type(colors) is np.ndarray:
    for cname, class_label in zip(color_names, np.unique(colors)):
      X_color = df[colors == class_label]
      ax.scatter(X_color[:, 0], X_color[:, 1], X_color[:, 2], marker="x", c=cname, label=f"Cluster {class_label}" if type(colors) is np.ndarray else None)
  else:
      ax.scatter(df.Type, df.Length, df.Freq, alpha=0.6, c=colors, marker="x", label=str(clusterSizes)  )

  ax.set_xlabel("PC1: Type")
  ax.set_ylabel("PC2: Length")
  ax.set_zlabel("PC3: Frequency")
  ax.set_title(title)
  
  if type(colors) is np.ndarray:
    #ax.legend()
    plt.gca().legend()
    
  
  plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
  plt.show()
Run Code Online (Sandbox Code Playgroud)

所以我调用我的函数来可视化集群模式:

plot_3d_transformed_data(pdf_km_pred,
                         f'Clustering rare URL parameters for data of date: {DATE_FROM}  \nMethod: KMeans over PCA \nn_clusters={n_clusters} , Distance_Measure={DistanceMeasure}',
                         colors=pdf_km_pred.prediction_km)

print(clusterSizes)
Run Code Online (Sandbox Code Playgroud)

遗憾的是我无法显示图例,我必须在 3D 绘图下手动打印集群成员。这是没有图例的输出,带有以下错误: No handles with labels found to put in legend. 在此处输入图片说明

我检查了这篇文章,但我无法弄清楚正确传递集群标签列表的功能有什么错误。我想更新该函数,以便我可以clusterSizes.index通过clusterSizes.size

预期输出:正如这里建议更好地使用legend_elements()来确定要显示的有用数量的图例条目并自动返回句柄和标签的元组。

更新:正如我在预期输出中提到的,应该包含一个集群标签图例和另一个集群大小图例(每个集群中的实例数)。它也可能通过单个图例报告此信息。请参阅下面的 2D 示例: 图片

Gui*_*ute 0

在创建第二个图例之前,您需要保存对第一个图例的引用并将其ax作为单独的艺术家添加到您的图例中。这样,第二次调用ax.legend(...)就不会删除第一个图例。

对于第二个图例,我只是为每种独特的颜色创建了一个圆圈并将其添加进去。我忘记了如何绘制真正的圆圈,所以我使用了 aLine2Dlw=0, marker="o"生成圆圈。

尝试使用图例bbox_to_anchorloc关键字以获得令您满意的结果。

我摆脱了所有依赖,plt.<something>因为这是忘记哪个方法附加到哪个对象的最佳方法。现在一切都在ax.<something>or中fig.<something>。当您有多个轴或想要将画布嵌入 PyQt 应用程序时,这也是正确的方法。plt不会做你所期望的事情。

最初的代码是@r-beginners提供的,我只是在它的基础上进行构建。

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

与问题无关:由于标记大小如何适用于 Circles,人们可以使用s = df["size"]**2而不是s = df["size"].