gpt4 book ai didi

python - 为 3D 绘图自动创建图例

转载 作者:行者123 更新时间:2023-12-04 11:38:59 24 4
gpt4 key购买 nike

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

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

最佳答案

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

关于python - 为 3D 绘图自动创建图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68895380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com