【问题标题】:How to Make Scipy Dendrogram Read Japanese Words/Terms如何让 Scipy Dendrogram 阅读日语单词/术语
【发布时间】:2017-06-06 06:16:47
【问题描述】:

我正在尝试通过日语单词/术语进行层次聚类,并使用scipy.cluster.hierarchy.dendrogram 绘制结果。但是,该图无法显示日语单词/术语,而是使用小矩形。起初,我在想这可能是因为当我创建字典时,键是 unicode 而不是日语(正如我问的问题 here)。然后有人建议我使用 Python3 来解决这个问题,最后我用日语单词而不是 unicode 制作字典键(作为我问的问题here)。然而,事实证明,即使我用日语单词/术语输入scipy.cluster.hierarchy.dendrogramlabel 参数,绘图仍然无法显示这些单词。我检查了几个类似的posts,但似乎仍然没有明确的解决方案。我的代码如下:

import pandas as pd
import numpy as np
from sklearn import decomposition
from sklearn.cluster import AgglomerativeClustering as hicluster
from scipy.spatial.distance import cdist, pdist
from scipy import sparse as sp ## Sparse Matrix
from scipy.cluster.hierarchy import dendrogram
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('ggplot')

## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz", 
    encoding='CP932')

## Set X as CSR Sparse Matrix 
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

def plot_dendrogram(model, **kwargs):
    # Children of hierarchical clustering
    children = model.children_

    # Distances between each pair of children
    # Since we don't have this information, we can use a uniform one 
      for plotting
    distance = np.arange(children.shape[0])

    # The number of observations contained in each cluster level
    no_of_observations = np.arange(2, children.shape[0]+2)

    # Create linkage matrix and then plot the dendrogram
    linkage_matrix = np.column_stack([children, distance, 
        no_of_observations]).astype(float)

    # Plot the corresponding dendrogram
    dendrogram(linkage_matrix, **kwargs)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

dictlist = []
temp = []
akey = []
avalue = []

for key, value in dict_index.items():
    akey.append(key)
    avalue.append(value)
    temp = [key,value]
    dictlist.append(temp)

avalue = np.array(avalue)

X_transform = X[:, avalue < 1000].transpose().toarray()

freq1000terms = akey
freq1000terms = np.array(freq1000terms)[avalue < 1000]

hicl_ward = hicluster(n_clusters=40,linkage='ward', compute_full_tree = 
    False)
hiclwres = hicl_ward.fit(X_transform)

plt.rcParams["figure.figsize"] = (15,6)

model1 = hiclwres
plt.title('Hierarchical Clustering Dendrogram (Ward Linkage)')
plot_dendrogram(model1, p = 40, truncate_mode = 'lastp', orientation = 
    'top', labels=freq1000terms[model1.labels_], color_threshold = 991)
plt.ylim(959,1000)
plt.show()

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    你需要给 matplotlib 一个有效的字体来显示日文字符。您可以使用以下代码从您的系统中找到可用的字体:

    import matplotlib.font_manager
    matplotlib.font_manager.findSystemFonts(fontpaths=None)
    

    它会给你一个matplotlib可以使用的系统字体列表:

    ['c:\\windows\\fonts\\seguisli.ttf',
     'C:\\WINDOWS\\Fonts\\BOD_R.TTF',
     'C:\\WINDOWS\\Fonts\\GILC____.TTF',
     'c:\\windows\\fonts\\segoewp-light.ttf',
     'c:\\windows\\fonts\\glsnecb.ttf',
     ...
     ...
     'c:\\windows\\fonts\\elephnti.ttf',
     'C:\\WINDOWS\\Fonts\\COPRGTB.TTF']
    

    选择一种支持日文字符编码的字体,并在代码开头将其作为参数提供给matplotlib,如下所示:

    import matplotlib.pyplot as plt
    plt.rcParams["font.family"] = "Yu Gothic" # I.E Yu Gothic, supports shift-jis
    

    这是一个全局参数设置,同一项目上的其他地块也将使用相同的字体系列。如果要更改单个文本,可以使用 font properties 的 matplotlib 文本对象。


    另外:如果您找不到/看到合适的字体,您可以下载像 code2000 这样的字体,安装它并以同样的方式使用它。 (要让字体显示在列表中,您可能需要清除 matplotlib 的缓存)

    【讨论】:

    • 感谢您的回答。 @umutto,我需要指定路径吗?
    • @tzu 我相信 matplotlib 可以从其名称中自动找到系统字体的路径,但它应该可以工作。为了安全起见,您可以从 font_manager 给您的列表中复制路径。
    • 我发现matplotlib只找到了以/Library/Fonts/foo.ttf开头的字体,但没有找到其他以/usr/X11R6/lib/X11/fonts/TTF/foo.ttf/System/Library/Fonts/foo.ttf/Users/username/Library/Fonts/foo.ttf开头的字体,错误消息为/usr/local/lib/python3.5/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['foo'] not found. Falling back to DejaVu Sans 。你能帮我解决这个问题吗? (我使用 Mac、Python3 和 Jupyter)非常感谢!
    • @tzu 对不起,我对 mac 不是很熟悉。但是findSystemFonts() 找到的字体给出了这个错误似乎很奇怪,也许清除/检查字体缓存。 (您可以使用matplotlib.get_cachedir() 找到位置)或查看有关如何在 matplotlib 中设置字体的其他答案。
    • 别担心,我会试着弄清楚。或者,有人可以帮忙吗?
    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多