Python数据分析之matplotlib(基础篇)

时间:2022-07-22
本文章向大家介绍Python数据分析之matplotlib(基础篇),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

matplotlib三种代码风格

import numpy as np
import os
import matplotlib.pyplot as plt
#notebook模式下
%matplotlib inline

pyplot

x=np.arange(0,10,1)
y=np.random.randn(len(x))
plt.plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
plt.title('pyplot')
plt.show()

pylab

#pylab不推荐使用
from pylab import *
x=arange(0,10,1)
y=randn(len(x))
plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
title('pylab')
show()

Object Oriented

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

整个图像是fig对象。我们的绘图中只有一个坐标系区域,也就是ax。此外还有以下对象。

  • Data: 数据区,包括数据点、描绘形状
  • Axis: 坐标轴,包括 X 轴、 Y 轴及其标签、刻度尺及其标签
  • Title: 标题,数据图的描述
  • Legend: 图例,区分图中包含的多种曲线或不同分类的数据
  • 其他的还有图形文本 (Text)、注解 (Annotate)等其他描述

Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。各个对象之间有下面的对象隶属关系:

# 推荐使用
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure() #定义图像的对象
ax=fig.add_subplot(111) #定义坐标系区域
ax.plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
ax.set_title('object oriented')
plt.show()

子图

x = np.arange(1,100)

fig = plt.figure()
ax1 = fig.add_subplot(221) # 定义2*2个子图(左一)
ax1.plot(x,x) # 绘制左一折线图

ax2 = fig.add_subplot(222)
ax2.plot(x,-x) # 绘制右一折线图(右一)

ax3 = fig.add_subplot(223)
ax3.plot(x,x*x) # 绘制左二折线图(左二)

ax4 = fig.add_subplot(224)
ax4.plot(x,np.log(x)) # 绘制右二折线图(右二)

plt.show()
x = np.arange(1,100)
plt.subplot(221) # 第一行的左图
plt.plot(x,x)
plt.subplot(222) # 第一行的右图
plt.plot(x,-x)
plt.subplot(212) # 第二整行
plt.plot(x,x*x)
plt.show()
#简化写法
fig,axes = plt.subplots(ncols=2,nrows=2) #定义子图为两行两列
ax1,ax2,ax3,ax4 = axes.ravel() #按照先行再列的顺序分配子图

x = np.arange(1,100)
ax1.plot(x,x)
ax2.plot(x,-x)
ax3.plot(x,x*x)
ax4.plot(x,np.log(x))
plt.show()

多图

fig1 = plt.figure() # plt派生一个图对象
ax1 = fig1.add_subplot(111)
ax1.plot([1,2,3],[3,2,1])

fig2 = plt.figure() # plt派生另一个图对象
ax2 = fig2.add_subplot(111)
ax2.plot([1,2,3],[1,2,3])

plt.show() # plt统一显示

参考

matplotlib核心剖析(http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html#commentform)