Python-Jupyter 中的命令无法可视化图表

问题描述 投票:0回答:1

我修改了link1link2并应用了其中所说的内容。但是,这些解决方案仍然不能解决我的问题。

我在jupyter中的python代码是:

#Librerias necesarias 
import pandas as pd
import seaborn as sn #Visualización
import numpy as np #complemento de pd
import matplotlib.pyplot as plt #graficar
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
#graficas 3D
%matplotlib notebook
#%pylab
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams['figure.figsize'] = (16, 9)
plt.style.use('ggplot')
#import warnings  #advertencias
#warnings.filterwarnings("ignore")

但是,当我运行这段代码时:

# Predicting the clusters
labels = kmeans.predict(X)
# Getting the cluster centers
C = kmeans.cluster_centers_
colores=['red','green','blue']
asignar=[]
for row in labels:
    asignar.append(colores[row])
 
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X[:, 0], X[:, 4], X[:, 4], c=asignar,s=10)
ax.scatter(C[:, 0], C[:, 4], C[:, 4], marker='*', c=colores, s=10)

它向我提示一个空图像:

这条消息:

我是Python新手,我没有看到这个问题。 会是什么?

python 3d jupyter
1个回答
0
投票

下面的代码示例呈现了类似的图。我认为您的原始代码的问题之一可能是

plt.style.use...
。我在下面修改了您的代码。

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

import sklearn.datasets
from sklearn.cluster import KMeans

#
#Mock data: 3 clusters in 3D space.
#
n_clusters = 3
n_features = 3
X, orig_labels = sklearn.datasets.make_blobs(
    n_samples=100, n_features=n_features, centers=n_clusters, cluster_std=0.8, random_state=0
)

#
#Fit and predict
#
kmeans = KMeans(n_clusters=n_clusters, n_init='auto').fit(X)
# Predicted labels and centres
predicted_labels = kmeans.predict(X)
predicted_centres = kmeans.cluster_centers_

#
#Plotting
#
#Initialise the figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(projection='3d')
# Change the viewing angle if desired
ax.view_init(azim=25, elev=25, roll=0)
colores=['tab:red', 'tab:green', 'tab:blue']

#Plot data coloured by the predicted label
pred_colours_per_pt = [colores[pred_label] for pred_label in predicted_labels]
ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=pred_colours_per_pt, s=50)

#Add this if you also want to see the original labels (sets edge colour)
# orig_colours_per_pt = [colores[orig_label] for orig_label in orig_labels]
# ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], edgecolors=orig_colours_per_pt,
#              s=50, linewidth=2.2, facecolor='none')

#Plot centres
colours_per_pt = [colores[pred_label] for pred_label in orig_labels]
ax.scatter3D(predicted_centres[:, 0],
             predicted_centres[:, 1],
             predicted_centres[:, 2],
             c=colores, marker='*', edgecolor='k', linewidth=2.5, s=300, alpha=1)

#Label axes
ax.set_xlabel('feature x')
ax.set_ylabel('feature y')
ax.set_zlabel('feature z')
ax.set_title('KMeans example')
© www.soinside.com 2019 - 2024. All rights reserved.