“无法评估 'x' 映射:plotnine 中的 'Cluster' 错误

"Could not evaluate the 'x' mapping: 'Cluster' error in plotnine

我运行此代码用于识别我需要使用 K 原型聚类的聚类数量,但我收到此错误

PlotnineError:“无法评估 'x' 映射:'Cluster'(原始错误:名称 'Cluster' 未定义)”

# Choose optimal K using Elbow method
cost = []
for cluster in range(1, 10):
    try:
        kprototype = KPrototypes(n_jobs = -1, n_clusters = cluster, init = 'Huang', random_state = 0)
        kprototype.fit_predict(dfMatrix, categorical = catColumnsPos)
        cost.append(kprototype.cost_)
        print('Cluster initiation: {}'.format(cluster))
    except:
        break
# Converting the results into a dataframe and plotting them

a = {'Cluster':range(1, 6), 'Cost':cost}
df_cost = pd.DataFrame.from_dict(a, orient='index')
df_cost.transpose()

# Data viz
plotnine.options.figure_size = (8, 4.8)
(
    ggplot(data = df_cost)+
    geom_line(aes(x = 'Cluster',
                  y = 'Cost'))+
    geom_point(aes(x = 'Cluster',
                   y = 'Cost'))+
    geom_label(aes(x = 'Cluster',
                   y = 'Cost',
                   label = 'Cluster'),
               size = 10,
               nudge_y = 1000) +
    labs(title = 'Optimal number of cluster with Elbow Method')+
    xlab('Number of Clusters k')+
    ylab('Cost')+
    theme_minimal()
)
有人知道吗?

您疏忽了数据转换代码。

这一行

df_cost.transpose()

应该是

df_cost = df_cost.transpose()