三维绘图图例的自动创建

2024-07-04 07:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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.enter image description here

我检查了这个post,但我无法找出函数中正确传递集群标签列表的错误。我想更新这个函数,这样我就可以通过clusterSizes.index演示集群标签,并通过clusterSizes.size演示它们的规模

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

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


Tags: 函数dfdatanp集群plt标签ax
2条回答

在可视化集群的函数中,需要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)

运行此示例代码,您将获得预期的图例句柄enter image description here

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

对于第二个图例,我只是为每种独特的颜色创建了一个圆圈,并将其添加到中。我忘了怎么画真正的圆,所以我用了Line2Dlw=0, marker="o"来画圆

使用图例的bbox_to_anchorloc关键字来获得令您满意的结果

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

最初的代码是由@r-初学者提供的,我只是在此基础上构建的

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

enter image description here

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

相关问题 更多 >

    热门问题