---
title: Python Seaborn 無法顯示中文
tags: matplotlib & Seaborn
---
Python Seaborn 無法顯示中文
==
在Seaborn 畫圖時,會遇到無法顯示中文的問題,以下提供三種方案解決。

## method 1
在每次畫圖前執行代碼:
```python=
sns.set_style("whitegrid",{"font.sans-serif":['Microsoft JhengHei']})
```
## method 2 (windows & ubuntu 皆適用)
一勞永逸
ps: 除了Step07以外 windows 跟 ubuntu 的操作皆相同, 以下範例使用 windows 作業系統
#### step01 找到機器上面 matplotlibrc 的位置
```python=
import matplotlib
matplotlib.matplotlib_fname()
#Out[]: 'D:\\anaconda3\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'
```
 
#### step02 用文字編輯器(Notepad++)打開matplotlibrc,找到 font.family 的區塊

 
#### step03 取消 font.family 與 font.sans-serif 的註解,並且在 font.sans-serif 的第一項插入想要的字體"Microsoft JhengHei"
Microsoft JhengHei => 微軟正黑體

 
#### Step04: 找到目前的 matplotlib 所預設的字體是什麼以及位置
```python=
from matplotlib.font_manager import findfont, FontProperties
findfont(FontProperties(family=FontProperties().get_family()))
#Out[]: 'D:\\anaconda3\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSans.ttf'
```

 
#### Step05: 從 C:\Windows\Fonts 資料夾中找到JhengHei 並複製

貼在桌面上

 
#### Step06: 將msjh.ttc 移動到Step04找到的資料夾中
('D:\\anaconda3\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSans.ttf')

 
#### Step07: 刪除.matplotlib快取資料夾
windows 作業系統:
在 ”C:\Users\您的使用者名稱” 找到 “.matplotlib “ 資料夾並刪除

 
linux 作業系統:
```python=
$cd ~/.cache/matplotlib
$rm -rf *.*
```
#### Step08: 最後,重新啟動 Jupyter Notebook;再畫一次剛剛的圖
```python=
import seaborn as sns
sns.barplot(y=df_counts.index, x=df_counts.values)
```

 
 
## method 3
暴力硬塞 (by 威霆)
before:
```python=
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname='/home/user/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/你的字體.ttf')
plt.pie(values, labels = labels, colors = colors, autopct='%.1f%%')
plt.show()
```

after:
```python=
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname='/home/user/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/你的字體.ttf')
patches,l_text,p_text =plt.pie(values, labels = labels, colors = colors, autopct='%.1f%%')
for t in l_text:
t.set_fontproperties(myfont) # 把每個文字設成中文字型
plt.show()
```

Reference:
1. https://orcahmlee.github.io/data-science/working-matplotlib-and-seaborn-with-chinese/
2. https://medium.com/marketingdatascience/%E8%A7%A3%E6%B1%BApython-3-matplotlib%E8%88%87seaborn%E8%A6%96%E8%A6%BA%E5%8C%96%E5%A5%97%E4%BB%B6%E4%B8%AD%E6%96%87%E9%A1%AF%E7%A4%BA%E5%95%8F%E9%A1%8C-f7b3773a889b
3. https://medium.com/marketingdatascience/%E8%A7%A3%E6%B1%BApython-3-matplotlib%E8%88%87seaborn%E8%A6%96%E8%A6%BA%E5%8C%96%E5%A5%97%E4%BB%B6%E4%B8%AD%E6%96%87%E9%A1%AF%E7%A4%BA%E5%95%8F%E9%A1%8C-f7b3773a889b
4. https://zhuanlan.zhihu.com/p/33463960