matplotlib 的安装:
- matplotlib是python的基础绘图库,他可以与NumPy一起使用,代替matlab使用.
- pip install matplotlib -i https://pypi.tuna.tsinghua.edu.com/simple;
官方链接: 官网 - -i : 表示安装源,国外源较慢,推荐国内几个源;
- 单个python环境时,使用jupyter notebook运行,多个python环境时,使用python -m notebook来运行(推荐使用虚拟环境,备注:jupyter安装时报错,也可创建虚拟环境来解决,其原因不赘);
- 可以绘制折线图,散点图,条形图,直方图,饼图
链接: 官方图形讲解.
Matplotlib
- 图片与子图
matplotlib所绘制的图位于图片(Figure)对象中,通过plt.figure生成一个新的图片:from matplotlib import pyplot as plt fig = plt.figure()
- 折线图
plt.figure(figsize = (14,8)) #宽,高 y = [15,13,14,15,17,20,25,26,27,22,18,15] x = range(0, 23, 2) x_t = [i/2 for i in range(48)] #刻度---> | x_l = ["{}h".format(i/2) for i in range(48)] #标签 ---> 0.0h y_t = range(min(y), max(y)+1) #左闭右开,故+1 plt.yticks(y_t) plt.xlabel("time") plt.ylabel("temperature") plt.title("temperature change!") plt.grid() plt.plot(x, y) plt.xticks(x_t,x_l, rotation=45) plt.savefig("temperature-change.jpg") plt.show()
运行如下图:
例子:
如果列表a表示10点到12点的每一分钟的气温,如何绘制折线图观察每分钟气温的变化
x = range(0,120)
y = [random.randint(18,39) for i in range(120)] #randint能够获取右边最大值
plt.plot(x,y)
x_t = range(0,120,10)
x_l = ["十点{}分".format(i) for i in range(0,60,10)]
x_l += ["十一点{}分".format(i) for i in range(0,60,10)]
## 字体设置方法
### 第一种方法:
#font = {'family' : 'SimHei', #字体格式只能为ttf
#'weight' : 'bold',
#'size' : 12}
#matplotlib.rc('font', **font)
### 第二种方法
#plt.rcParams['font.sans-serif'] = ['SimHei']
#plt.rcParams['axes.unicode_minus'] = False
### 第三种方法
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc", size=12)
plt.xticks(x_t,x_l,rotation=45,FontProperties=font)
plt.show()