matplotlib 学习

简介

安装

总结

matplotlib 有乱码

1、下载中文字体(黑体,看准系统版本)
2、找到matplotlib字体文件夹,例如:matplotlib/mpl-data/fonts/ttf,将SimHei.ttf拷贝到ttf文件夹下面
3、修改matplotlib配置文件:

1
2
3
sudo vim /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data/matplotlibrc
# 删除font.family和font.sans-serif两行前的#,并在font.sans-serif后添加中文字体Microsoft YaHei, ...(其余不变)

4、下面代码检查可使用的字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
#print(mat_fonts)
output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True)
#print( '*' * 10, '系统可用的中文字体', '*' * 10)
#print (output)
zh_fonts = set(f.split(',', 1)[0] for f in output.decode('utf-8').split('\n'))
available = mat_fonts & zh_fonts
print ('*' * 10, '可用的字体', '*' * 10)
for f in available:
print (f)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

import matplotlib.pyplot as plt
import matplotlib
from matplotlib.font_manager import *


plt.rcParams['font.sans-serif']=['Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题


price = [39.5, 39.9, 45.4, 38.9, 33.34]
"""
绘制水平条形图方法barh
参数一:y轴
参数二:x轴
"""
plt.barh(range(5), price, height=0.7, color='steelblue', alpha=0.8) # 从下往上画
plt.yticks(range(5), ['tom', '当当网', '中国图书网', '京东', '天猫'])
plt.xlim(30,47)
plt.xlabel("价格")
plt.title("不同平台图书价格")
for x, y in enumerate(price):
plt.text(y + 0.2, x - 0.1, '%s' % y)
plt.show()

或者直接指定字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.font_manager import *


myfont = FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
matplotlib.rcParams['axes.unicode_minus']=False


price = [39.5, 39.9, 45.4, 38.9, 33.34]
"""
绘制水平条形图方法barh
参数一:y轴
参数二:x轴
"""
plt.barh(range(5), price, height=0.7, color='steelblue', alpha=0.8) # 从下往上画
plt.yticks(range(5), ['tom', '当当网', '中国图书网', '京东', '天猫'],fontproperties=myfont)
plt.xlim(30,47)
plt.xlabel("价格",fontproperties=myfont)
plt.title("不同平台图书价格",fontproperties=myfont)
for x, y in enumerate(price):
plt.text(y + 0.2, x - 0.1, '%s' % y)
plt.show()