matplotlib使用

2018-12-25  本文已影响0人  萌木盖

import matplotlib.pyplot as plt

figure.savefig的选项

!mkdir "./img"
plt.plot(x,y)
plt.savefig("./img/fig.jpg")
# 添加子轴面,
#一个图层里面可以方多个图像,每一个图像都是该图层的一个子轴面
# 1、取出plt的图层对象
figure = plt.figure(figsize=(12,3))
# 2、向图层中增加子轴面
axes1 = figure.add_subplot(1,3,1) 
# 获取到子轴面对象,可以把图像画在里面
axes1.plot(x,y)
# 三个参数分别多少行、多少列、第几个(从左到右,从上到下)
# 3、在子轴面中绘制图像
axes2 = figure.add_subplot(1,3,2)

axes3 = figure.add_subplot(1,3,3)

axes2.plot(x,np.cos(x),color="m",linestyle="-.")

axes3.plot(x,np.tan(x),color='g',linestyle=":")

#加网格
axes1.grid(b=True,c="g",linestyle=":")
axes2.grid(c='r',linestyle="--")

字符串 数值 字符串 数值
best 0 center left 6
upper right 1 center right 7
upper left 2 lower center 8
lower left 3 upper center 9
lower right 4 center 10
right 5
- plt.legend(["y=x^2","y=2x","y=cos(x)"],loc="best")

设置plot的风格和样式

颜色值的方式

颜色 别名 HTML颜色名 颜色 别名 HTML颜色名
蓝色 b blue 绿色 g green
红色 r red 黄色 y yellow
青色 c cyan 黑色 k black
洋红色 m magenta 白色 w white

线条风格设置

线条风格 描述 线条风格 描述
'-' 实线 ':' 虚线
'--' 破折线 'steps' 阶梯线
'-.' 点划线 'None' / ',' 什么都不画
标记 描述 标记 描述
'1' 一角朝下的三脚架 '3' 一角朝左的三脚架
'2' 一角朝上的三脚架 '4' 一角朝右的三脚架
标记 描述 标记 描述
'.' 'x' X
'*' 星号 '+' 加号
',' 像素
标记 描述 标记 描述
'o' 圆圈 'D' 菱形
'd' 小菱形 '','None',' ',None
标记 描述 标记 描述
'_' 水平线 '|' 水平线
lines = plt.plot(x,y,x,x**2)
# 通过setter方法对属性进行设置
lines[0].set_color("r")
lines[0].set_marker(">")
lines[1].set_ls("-.")
lines[1].set_lw(10)
参数 描述 参数 描述
color或c 线的颜色 linestyle或ls 线型
linewidth或lw 线宽 marker 点型
markeredgecolor 点边缘的颜色 markeredgewidth 点边缘的宽度
markerfacecolor 点内部的颜色 markersize 点的大小

X、Y轴坐标刻度

x = np.linspace(-5,5,50)
y = np.sin(x)
plt.plot(x,y,c='r')
# 设置x轴坐标的标记
plt.xticks(np.linspace(-np.pi,np.pi,5),
           ("-pi","-pi/2","0","pi/2","pi"),size=20,rotation=60)
# y轴留三个
plt.yticks([-1,0,1],["min",0,'max'])

面向对象方法设置刻度

# 坐标标签与刻度属于图层面板
figure = plt.figure(figsize=(12,5))

axes = figure.add_subplot(111)

axes.plot(x,y,c="m")

axes.set_xticks(np.linspace(-np.pi,np.pi,5)) # 这个方法设置下标的位置
axes.set_xticklabels(["-pi","-pi/2",0,"pi/2","pi"],size=10)
plt.plot(x,y)
plt.xticks(np.linspace(-np.pi,np.pi,5),
           ["-$\pi$","-$\pi$/2",0,"$\pi$/2","$\pi$"])

其他2D图形

直方图

【直方图的参数只有一个x!!!不像条形图需要传入x,y】

hist()的参数

x = np.random.randint(0,10,size=100)
print(x)
plt.hist(x,bins=20,normed=True,color='r',orientation="vertical")
# bins参数代表是划分多少个区间,normed参数代表是否归一化

条形图

【条形图有两个参数x,y!】

bar()、barh()

饼图

【饼图也只有一个参数x!】

labels = ["China","USA","EU","Japan","UK","France","Others"]
data = np.array([0.12,0.18,0.15,0.06,0.03,0.025,0.465])

plt.pie(data,labels=labels,labeldistance=1,autopct="%0.2f%%",
        pctdistance=0.8,explode=[0.2,0.2,0,0,0.5,0.1,0.1],shadow=True,
       startangle=180
       )

饼图阴影、分裂等属性设置

散点图

【散点图需要两个参数x,y,但此时x不是表示x轴的刻度,而是每个点的横坐标!】

x = np.random.randn(1000)
y = np.random.randn(1000)

# 随机生成1000中颜色
colors = np.random.rand(3000).reshape((1000,3))
# 随机生成1000个大小
size = np.random.randint(1,100,size=1000)

plt.scatter(x,y,color=colors,s=size,marker="d")

图形内的文字、注释、箭头

控制文字属性的方法:

Pyplot函数 API方法 描述
text() mpl.axes.Axes.text() 在Axes对象的任意位置添加文字
xlabel() mpl.axes.Axes.set_xlabel() 为X轴添加标签
ylabel() mpl.axes.Axes.set_ylabel() 为Y轴添加标签
title() mpl.axes.Axes.set_title() 为Axes对象添加标题
legend() mpl.axes.Axes.legend() 为Axes对象添加图例
figtext() mpl.figure.Figure.text() 在Figure对象的任意位置添加文字
suptitle() mpl.figure.Figure.suptitle() 为Figure对象添加中心化的标题
annnotate() mpl.axes.Axes.annotate() 为Axes对象添加注释(箭头可选)

所有的方法会返回一个matplotlib.text.Text对象

注释

annotate()
xy参数设置箭头指示的位置,xytext参数设置注释文字的位置
arrowprops参数以字典的形式设置箭头的样式
width参数设置箭头长方形部分的宽度,headlength参数设置箭头尖端的长度,
headwidth参数设置箭头尖端底部的宽度,
facecolor设置箭头颜色
shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值)

3D图

from mpl_toolkits.mplot3d import Axes3D
ax = plt.subplot(projection="3d")
ax.scatter3D(samples["2006世界杯"],samples["2010世界杯"],samples["2007亚洲杯"],c=y_)
centers = km.cluster_centers_
ax.scatter3D(centers[:,0],centers[:,1],centers[:,2],c='r')
上一篇下一篇

猜你喜欢

热点阅读