数据小站
数据科学成长之路

matplotlib手册

matplotlib的图像都位于Figure对象中。你可以用plt.figure创建一Figure.

在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个subplot Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域

创建图表对象

fig 和subplot对象创建

画布与绘图 fig和subplot对象
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)

plt.subplots( )方法可以直接创建图表对象

plt.subplots( nrows = , nclos = , sharex = , sharey = ) , sharex/y 指定subplot对象是否共享相同的xy刻度,调节其中一个刻度将影响所有subplot。
fig,axes=plt.subplots(2,3) ==> axes是一个可迭代对象, 通过数组索引选取目标位置,axes[0,1]

子图subplot间距调整

plt.subplots_adjust(left=None,bottom=None,rigth=None,top=None,wspace=None,hspace=None)

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(0,2):
    for j in range(0,2):
        axes[i,j].hist(np.random.randn(500),bins=50)
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()
设置间距时,plt本身不会坚持各个子图直接的轴标记是否能重叠,在合并时,需要手动设置xy轴刻度标记。

线形设置

plt.plot(x, y, color = ,)

颜色Colors 标记Markers 线形Line Styles 可以使用缩写

color 可以设置 : b g r c m y k w

linestyles 可以设置 : “-” “–” “-.” “:”

marker标记可以设置 . , o v ^ < > 1 2 4 8 s p * ,具体参考文档

图表装饰项通用设置: 图例 刻度 标签设置

xlim、 xticks 、xticklabels ,分别控制图表的刻度范围, 刻度位置, 刻度标签。

使用有两种方式, 不带参数时,返回当前的参数范围,带参数时,对当前的轴进行设置。

plt.xlim() 返回当前x轴的绘图范围

plt.xlim([0,10]) 将x轴的绘图范围设置为0-10

通过plt调用上诉方法时,是对当前或最新创建的subplot起作用。

操作subplot各自的设置时,subplot对象上有相应的方法

plt.xlim -> ax.get_xlim / ax.set_xlim

plt.xticks -> ax.set_xticks

subplot的其他设置方法: set_xticklabels 、 set_xlabel 、 set_title

图例设置

plt.legend() ax.legend() 自动创建图例

ax.plot(…, label = ‘图例名’)

ax.legend(loc = ”) loc设置图例位置,默认best

不需要设置图例时,绘图时不设置label,或者label设置为 nolegend。

图例注释 .text .arrow .annotate

ax.text(x,y, ‘文本内容’ , fontsize=10, family=’monospace)

图像保存savefig

plt.savefig(fname ,dpi , format ,edgecolor ,bbox_inches)

dpi 分辨率,默认100,每英寸点数

format 文件个格式, png pdf svg ps eps 等

facecolor / edgecolor 图片的背景,默认白色

bbox_inches 图表需要保存的部分。设置为tight时,将尝试剪除图片周围空白部分。

maplotlib配置项

全局配置系统方法rc(),

plt.rc(‘figure’, figgsize=(10,10))

设置边框 gac

ax=plt.gac() #获取坐标轴信息

ax.spines[‘top’].set_color(‘none’) #设置头部边框为空

ax.spines[‘top’].set_color(‘none’)





9.pandas绘图
s.plot(use_index=False/True) ==>series
series.plot(kind,logy,use_index,rot,xticks,yticks,xilm,ylim,grid) ==> s.plot(kind=’bar’,ax=axes1..)
df.plot(subplots,sharex,sharey,figzise,title,legend,sort_columns)
10.选择绘图ax
plt.sca(ax) 用来指定绘制的区域
11.中文
程序中修改字体 ==> plt.rcParams[‘font.sans-serif’]=[‘SimHei’]
修改配置文件
plt.rcParams[‘font.sans-serif’]=[‘SimHei’] #用来正常显示中文标签
plt.rcParams[‘axes.unicode_minus’]=False #用来正常显示负号
12.线形
折线 ==> .plot(x,y,linestyle=,marker=,color=)
散点 ==> .scatter(x,y,”-o”)
直方图 ==> .hist()
13.多图与子图
在当前的subplot对象上.plot画多图
绘制多图,plt.subplot()调用多次,覆盖
fig1=plt.figure()
plt.subplot(221)
plt.subplot(222)
plt.subplot(212)
14.对数坐标轴
x 轴为对数坐标轴 ==> ax.semilogx(x,y)
y 轴为对数坐标轴 ==> ax.semilogy(x,y)
双对数坐标轴 ==> ax.loglog(x,y)
15.文字说明
text()可以在图中的任意位置添加文字
xlable(), ylable()用于添加x轴和y轴标签
title()用于添加图的题目
plt.text(X,Y,”text”) X,Y指定文本的位置
16.文本注释
plt.annotate()在使用annotate时,要考虑两个点的坐标:被注释的地方xy(x, y)和插入文本的地方xytext(x, y)
plt.annotate(‘local max’, xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor=’black’, shrink=0.05),
)
17.设置轴记号
plt.xticks()/plt.yticks()
plt.xticks()([0,10,20,30],[‘a’,’b’,’c’]) 轴标记作用为显示x/y轴中指定位置的刻度,可以在指定刻度的时候指定标签
18.设置axes位置
19.LaTex
LaTex使用
20.移动脊柱
每个axes对象有四条脊柱(上下左右),分别用axes.spines[‘left/right/top/bottom’]选定
ax.spines[‘right’].set_color(‘none’)

常见图形

热力图

pandas中,dataframe都是数字时, .corr()计算特征之间的协方差矩阵,协方差矩阵的热力图

coor = data.corr()
plt.imshow(coor)
plt.xticks(range(len(coor)), coor.columns, rotation=45)
plt.yticks(range(len(coor)), coor.index)
plt.show()

赞(0) 打赏
未经允许不得转载:技术文档分享 » matplotlib手册

评论 抢沙发