簡體   English   中英

如何將 label 附加到 Python 中的樹狀圖

[英]How to attach label to dendrogram in Python

我很難標記樹狀圖,每次嘗試時都會收到錯誤消息。 這是我的代碼: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline

import scipy.cluster.hierarchy as shc
plt.figure(figsize=(20, 50))  
plt.title("Dendrograms")  
dend = shc.dendrogram(shc.linkage(df, method='ward'), leaf_font_size=12, orientation='right', labels=Country)

錯誤:

ValueError                                Traceback (most recent call last)
<ipython-input-95-2310a4d5ca2d> in <module>
      2 plt.figure(figsize=(20, 50))
      3 plt.title("Dendrograms")
----> 4 dend = shc.dendrogram(shc.linkage(df, method='ward'), leaf_font_size=12, orientation='right', labels='Country')

~\Anaconda3\lib\site-packages\scipy\cluster\hierarchy.py in linkage(y, method, metric, optimal_ordering)
   1040         raise ValueError("Invalid method: {0}".format(method))
   1041 
-> 1042     y = _convert_to_double(np.asarray(y, order='c'))
   1043 
   1044     if y.ndim == 1:

~\Anaconda3\lib\site-packages\scipy\cluster\hierarchy.py in _convert_to_double(X)
   1562 def _convert_to_double(X):
   1563     if X.dtype != np.double:
-> 1564         X = X.astype(np.double)
   1565     if not X.flags.contiguous:
   1566         X = X.copy()

ValueError: could not convert string to float: 'USA'

df中有 12 個功能,我想 label 使用國家/地區名稱的樹狀圖。 但是,如果我在沒有指定標簽的情況下刪除Country ,它將使用0、1、2、...、n代替國家名稱,因為它沒有指定 plot 。 但是,如果我在 df 中指定標簽並包含Country ,則會出現上述錯誤。 請問我該怎么做 go

這個問題已經有幾個月了,但還沒有答案。 所以我會給一個。

對於解決方案,我希望Country是您的df DataFrame 中的一列。 樹形dendogramlabel 選項不需要您的實際數據列df ,而是類似序列/列表/數組的結構。 要使您的代碼正常工作,您只需刪除Country列,然后將 rest 傳遞給linkage function 並單獨設置Country列。

使用名為“國家”的列Country的示例的修復方法是將dendogram行替換為以下內容:

shc.dendrogram(shc.linkage(df.drop("country", axis=1), method='ward'), leaf_font_size=12, orientation='right', labels=df["country"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM