Python Matplot中文顯示完美解決方案

來源:互聯網
上載者:User

標籤:字型庫   com   技術   ber   分享   需要   params   ams   app   

原因與現象

Matplot是一個功能強大的Python圖表繪製庫,很遺憾目前版本內建的字型庫中並不支援中文字型。所以如果在繪製內容中需要顯示中文,那麼就會顯示為方格字元。

解決辦法

有一個較為完美的解決方案,通過掃描Matplot內建字型庫以及系統字型庫,尋找能夠支援的中文字型,如果能夠找到的話,就設定第一個為Matplot的字型熟悉。

代碼如下:

import matplotlib.pyplot as pltfrom matplotlib.font_manager import FontManagerfrom pylab import mplimport subprocessdef get_matplot_zh_font():    fm = FontManager()    mat_fonts = set(f.name for f in fm.ttflist)    output = subprocess.check_output(‘fc-list :lang=zh -f "%{family}\n"‘, shell=True)    zh_fonts = set(f.split(‘,‘, 1)[0] for f in output.split(‘\n‘))    available = list(mat_fonts & zh_fonts)    print ‘*‘ * 10, ‘可用的字型‘, ‘*‘ * 10    for f in available:        print f    return availabledef set_matplot_zh_font():    available = get_matplot_zh_font()    if len(available) > 0:        mpl.rcParams[‘font.sans-serif‘] = [available[0]]    # 指定預設字型        mpl.rcParams[‘axes.unicode_minus‘] = False          # 解決儲存映像是負號‘-‘顯示為方塊的問題

在繪圖之前,調用set_matplot_zh_font()設定一下就可以了。

效果

如所示:

Python Matplot中文顯示完美解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.