文章目录

  • 1.基础知识
  • 柱状图
  • 直方图
  • 饼图
  • 修饰图
  • 散点图
  • 绘制图像
  • 2.figure和axes使用
  • figure
  • 3.基础知识


Matplotlib

​官方文档​

1.基础知识

导入依赖

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

画一张图

fig, ax = plt.subplots()  # 创建一个画板和轴
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # Plot some data on the axes.

matplotlib使用文档(不断补充)_坐标轴


关于画板

matplotlib使用文档(不断补充)_数据_02

柱状图

y = np.array([1,13,25,17,36,21,16,10,15])
plt.bar(range(9),y,0.6, align = 'center',color='steelblue',alpha=0.2)# 柱状图(x,y,粗度,a透明度,color)
for x,y in enumerate(y):
plt.text(x,y,'%d' %y ,ha='center') # 给柱状图添加图示
plt.show()

matplotlib使用文档(不断补充)_柱状图_03

直方图

y = np.array([1,13,25,17,36,21,16,10,15])
plt.hist(y, bins=5,color='gray')# 直方图(x,y,粗度,a透明度,color)
plt.show()

matplotlib使用文档(不断补充)_matplotlib_04

饼图

x = np.array([5,6,7,8])
plt.pie(x)
plt.show()

matplotlib使用文档(不断补充)_matplotlib_05

修饰图

x = np.array([1,2,3,4,5,6,7,8])
y = np.array([3,5,8,6,2,6,7,15])
plt.fill_between(x,y,0,color='green') # 修饰图
plt.show()

matplotlib使用文档(不断补充)_matplotlib_06

散点图

n = 1024
#均值为0, 方差为1的随机数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
#计算颜色值
color = np.arctan2(y, x)
#绘制散点图
plt.scatter(x, y, s = 75, c = color, alpha = 0.5)#s设置大小,marker设置样式
#设置坐标轴范围
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))

scatter散点图

matplotlib使用文档(不断补充)_坐标轴_07

绘制图像

#绘制图片
a = np.linspace(0, 1, 9).reshape(3, 3)
#显示图像数据
plt.imshow(a, interpolation = 'nearest', cmap = 'bone', origin = 'lower')
#添加颜色条
plt.colorbar()
#去掉坐标轴
plt.xticks(())
plt.yticks(())
plt.show()

matplotlib使用文档(不断补充)_matplotlib_08

2.figure和axes使用

figure

我们可以把figure看做画板,将axes看做画纸,如下图,在一个画板上我们可以绘制多个axes,也可以将多个axes绘制在一个位置上,subplot也可以看做一种axes。

matplotlib使用文档(不断补充)_数据_09


关于面向对象绘图和面向函数绘图

rect = [0.1,0.1,0.8,0.8]
fig = plt.figure()
ax1 = fig.add_axes(rect,label='axes1')#axes1 = fig.add_axes(*args, **kwargs)
sca = ax1.scatter([1,3,5],[2,1,2])
plt.show()

直接使用figure()画简单的图

x = np.linspace(-1, 1, 50)
#figure,指定figure的编号并指定figure的大小, 指定线的颜色, 宽度和类型
#一个坐标轴上画了两个图形
y1 = x**2
y2 = np.sin(x)
plt.figure(num = 1, figsize = (5, 5))
plt.plot(x, y1)
plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')
plt.show()

matplotlib使用文档(不断补充)_matplotlib_10


在一个figure绘制多个子图

plt.figure()
#绘制第一个图
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
#绘制第二个图
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 1])
#绘制第三个图
plt.subplot(2, 3, 5)
plt.plot([0, 1], [0, 1])
#绘制第四个图
plt.subplot(2, 3, 6)
plt.plot([0, 1], [0, 1])
plt.show()

matplotlib使用文档(不断补充)_数据_11

3.基础知识

​%matplotlib​​​主要用于当我们在jupyter notebook使用plt画图,图像可以直接显示在代码单元格下面,生成的图也位于jupyter notebook中。​​Purpose of “%matplotlib inline”​

参考
​​Python第三方库matplotlib(2D绘图库)入门与进阶​​python数据可视化 | DataFrame.plot()函数绘制数据图
Matplotlib 常用画图命令总结:使用 Python 在论文中画出一手漂亮的数据图
利用pandas进行数据分组及可视化