机器学习——科学数据包(八)可视化:颜色样式、子图、多图、坐标
颜色
- 八种內建默认颜色缩写
b:blue
g:green
r :red
c :cyan
m:magenta
y:yellow
k:black
w:white - 其他颜色表示方法
- 灰色阴影
- html 十六进制
- RGB元组
点、线样式
-
23种点形状,注意:不同点形状默认使用不同颜色
“.” :point
“,” :pixel
“o” :circle
“v” :triangle_down
“^” :triangle_up
“<” :triangle_left
“>” :triangle_right
“1” :tri_down
“2” :tri_up
“3” :tri_left
“4” :tri_right
“8” :octagon
“s” :square
“p” :pentagon
“*” :star
“h” :hexagon1
“H” :hexagon2
“+”:plus
“x” :x
“D” :diamond
“d” :thin_diamond -
线型
实线: -
虚线: - -
点划线:-.
点线: : -
样式字符串
可以将颜色,点型,线型写成一个字符串:
cx–
mo:
kp-
pyplot pylab 面向对象
- pyplot :经典高层封装,到目前为止,我们所用的都是pyplot
- pylab :将Matplotlib 和 Numpy合并模块、模拟Matlab编程环境
- 面向对象的方式:Matplotlib的精髓,更基础以及底层的方式
优劣:
- pyplot:简单易用。交互使用时方便,可以根据命令实时作图,但底层定制能力不足
- pylab:完全封装,环境最接近Matlab。不推荐使用
- 面向对象(Object-Oriented):接近Matplotlib基础和底层的方式,难度稍大,但定制能力强,而且是Matplotlib的精髓
- 总结:实战中推荐,根据需求,综合使用pyplot和面向对象方式,显示导入numpy
pylab
from pylab import *
x = arange(0,10,1)
y = randn(len(x))
plot(x,y)
title('pylab')
show()
面向对象
#面向对象
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure() #创建一个对象
ax=fig.add_subplot(111) #创建坐标系
ax.plot(x,y) #画图
ax.set_title('object oriented') #创建标题
子图
- Matplotlib对象简介
- FigureCanvas
- Figure
- Axes
实践
- fig=plt.figure()
- Figure 实例
- 可以添加Axes实例
ax=fig.add_subplot(111)
- 返回Axes实例
- 参数一:子图总行数
- 参数二:子图总列数
- 参数三:子图位置
- 在Figure上添加Axes的常用方法
x=np.arange(1,100)
fig=plt.figure()
ax1=fig.add_subplot(221)
ax1.plot(x,x)
ax2=fig.add_subplot(222)
ax2.plot(x,-x)
ax3=fig.add_subplot(223)
ax3.plot(x,x**2)
ax4=fig.add_subplot(224)
ax4.plot(x,np.log(x))
plt.show()
网格
对象/plt.grid(True) # 生成默认网格
对象/plt.grid(color='r',linestyle=':',linewidth='2') # 生成设置样式的网格
图例
plt.legend(loc=,ncol=)#loc=1,2,3,4 ncol=列数
坐标轴范围
# 查看坐标轴范围
对象/plt.axis()
# 设置坐标轴范围 同时设置x,y
对象/plt.axis([x最小值,x最大值,y最小值,y最大值])
# 设置x坐标轴范围
对象/plt.xlim([x最小值,x最大值])
# 设置y坐标轴范围
对象/plt.ylim([y最小值,y最大值])
坐标轴刻度
plt/对象.locator_params(nbins=20) # 将x和y轴的段数调整为20
plt/对象.locator_params('y',nbins=20) # 将y轴的段数调整为20
import matplotlib as mpl # 多导入一个包
fig = plt.figure()
ax = plt.gca()
# 调整日期样式
date_format = mpl.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(date_format)
# 自适应日期互不遮挡
fig.autofmt_xdate()
# 使用plot_date()绘制
plt.plot_date(dates,y,linestyle='-',marker='')
添加坐标轴
plt.twinx()
plt.twiny()