使用Matplotlib绘图

使用方法类似于Matlab

数据基于 class ’numpy.ndarray'

也可以基于 class ’list'

导入库

# 导入库
import matplotlib.pyplot as plt
import numpy

数据的导入

# 基于ndarray的数据
x = np.array([1,2,3,4,5])
y = np.array([6,7,8,9,0])
# 基于list的数据
z = [1,4,3,5,6,7]

绘图

# 绘图函数的使用方法与Matlab相同
# 颜色/线型/标记的设置和Matlab相同
# 或者使用名值对指定绘图参数

# 折线图
plt.plot(x,y)
# 'r-x'            # 红色 单实线 ‘x’标记
# linewidth = 5    # 线粗为5

# 条形图
plt.bar(x,y)

# 火柴图
plt.stem(x,y)

# 散点图
plt.scatter(x,y)
# s = 40                        # size
# c = 'red'                     # color
# c = (0,0,0.87)                # RGB color
# c = y,cmap = plt.cm.Blues     # 颜色映射 不同的值深度不同
# edgecolor='none'              # 数据点轮廓

图像设置

通常情况下可以理解为状态机参数的调整

因此后面的语句会覆盖之前的代码

坐标轴

# 设置x,y轴的显示范围
plt.xlim((-1,1))
plt.ylim((0,3))

# 也可以用axis设置
plt.axis([-1,1,0,3])

图表标题

# 设置图表标题
pl.title("title")

坐标轴标签

plt.xlabel('xname')
plt.ylabel('yname')
# 设置字体  fontproperties='SimHei'
# 设置字号  fontsize=14

坐标轴刻度

# 设置坐标轴的刻度
# 使用numpy,设置-1到1,均分成5份
# 当范围大于xlim指定的范围时会扩展
plt.xticks(np.linespace(-1,1,5))

# 使用字符串list命名
plt.yticks([-5,0,5], ["negative","neutral","positive"])

# 可以设置标记刻度的样式
plt.tick_params(axis="both", labelsize=14)

四边边框设置

# 获得四边边框对象
ax = plt.gca()

# 设置颜色,设置为none可以隐藏
ax.spines['top'].set_color('none')
# 设置坐标轴位置,可以设置横轴经过数据的0点
ax.spines['bottom'].set_position(('data',0))
# 设置坐标轴的位置,可以设置纵轴在最右端
ax.spines['left'].set_position(('axes',1))
# 设置坐标轴上标注的位置,可以设置在纵轴的右侧
ax.spines['left'].set_ticks_position('right')

图例设置

# 方法一:在plot绘图时指定label的内容
lab_sin = "this is a sinesoidal wave"
plt.plot(x,y,label = lab_sin)
plt.legend()

# 方法二:在plot绘图时获得句柄,在legend中指定内容
han1,=plt.plot(x,y)
han2,=plt.plot(x,z)
plt.legend(handles=[han1,han2], labels=["y_values","z_values"])

# loc='best'                 # 指定图例的位置,‘best’自动分配最佳位置

图像输出

# 显示图像
# 在plt.show()之前的部分会画在一张图里 没有plt.show()不画图
plt.show()

# 修改图像的输出
plt.figure(figsize=(10,6))
# dpi = 128                    # 屏幕分辨率

# 保存图像
plt.savefig("file_name.png")
# bbox_inches='tight'          # 将图像边缘白边裁掉
Lei Yang
Lei Yang
PhD candidate

My research interests include visual speech recognition and semantics segmentation.