为 3D 图自动创建图例

Automated legend creation for 3D plot

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

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()

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

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)

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

我检查了这个 post,但我无法弄清楚正确传递集群标签列表的函数有什么错误。我想更新函数,以便我可以通过 clusterSizes.index 演示集群标签,并通过 clusterSizes.size

演示集群标签

预期输出: 正如 here 建议更好地使用 legend_elements() 来确定要显示的有用图例条目数和 return自动处理和标签的元组。

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

在可视化集群的函数中,您需要 ax.legend 而不是 plt.legend

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import numpy as np
import pandas as pd

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()
    
  
  ax.legend(bbox_to_anchor=(.9,1), loc="upper left")
  plt.show()

clusterSizes = 10

test_df = pd.DataFrame({'Type':np.random.randint(0,5,10),
                        'Length':np.random.randint(0,20,10),
                        'Freq':np.random.randint(0,10,10),
                        'Colors':np.random.choice(color_names,10)})

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

运行 这个示例代码,你将有预期的图例句柄

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

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

玩转图例的 bbox_to_anchorloc 关键字以获得令您满意的结果。

我摆脱了依赖 plt.<something> 的一切,因为这是忘记哪个方法附加到哪个对象的最佳方式。现在一切都在 ax.<something>fig.<something> 中。当您有多个轴时,或者当您想将 canvas 嵌入 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()

与问题无关:because of how markersize works for circles,可以使用 s = df["size"]**2 而不是 s = df["size"]