Fork me on GitHub

matplotlib基础学习

根据莫凡Python学习的笔记记录

In [2]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,1,50)
y = 2*x + 1

plt.plot(x,y)
plt.show()
In [7]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2

plt.figure(num=1,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')

plt.show()
In [16]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2

plt.figure(num=1,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')

# x,y轴的取值范围
plt.xlim(-1,2)
plt.ylim((-2,3))
# x,y轴的标签
plt.xlabel('x axis')
plt.ylabel('y axis')
# x,y轴的单位间隔
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.2,3],[r'$really\ bad$',r'$bad\ \alpha$',\
                               r'$normal$',r'$good$',r'$awsome$'])

plt.show()
In [20]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2

plt.figure(num=1,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')

# x,y轴的取值范围
plt.xlim(-1,2)
plt.ylim((-2,3))
# x,y轴的标签
plt.xlabel('x axis')
plt.ylabel('y axis')
# x,y轴的单位间隔
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.2,3],[r'$really\ bad$',r'$bad\ \alpha$',\
                               r'$normal$',r'$good$',r'$awsome$'])

# gca = 'get current axis'
# spines设置figure的边框
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# 设置坐标轴的交叉点(0,0)
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))


plt.show()
In [23]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2

# 图框号码,大小
plt.figure(num=1,figsize=(8,5))

# x,y轴的取值范围
plt.xlim(-1,2)
plt.ylim((-2,3))
# x,y轴的标签
plt.xlabel('x axis')
plt.ylabel('y axis')
# x,y轴的单位间隔
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.2,3],[r'$really\ bad$',r'$bad\ \alpha$',\
                               r'$normal$',r'$good$',r'$awsome$'])

# gca = 'get current axis'
# spines设置figure的边框
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# 设置坐标轴的交叉点(0,0)
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 绘图
l1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down')
l2, = plt.plot(x, y2, label='up')

# 设置图例
plt.legend(handles=[l1,l2], labels=['down_line','up_line'], loc='best')

plt.show()
In [29]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y = x*2 + 1

plt.figure(num=1, figsize=(8,5))
plt.plot(x,y)
# 设置边框+移动坐标轴
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
# 标注(X0,Y0)点的信息
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0,x0],[0,y0],'k--',linewidth=2.5)  # k means black
# 设置标注点的样式
plt.scatter([x0],[y0],s=50,color='b')
# 添加注释annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0,y0), xycoords='data', xytext=(+30,-30),\
            textcoords='offset points', fontsize=16,\
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))
# 添加注释text
plt.text(-3.7, 3, r'$This\ is\ some\ text.\mu\ \sigma_i\ \alpha_t$',\
        fontdict={'size': 16,'color': 'r'})

plt.show()
In [32]:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 调整坐标
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
    # alpha通道设置透明度,zorder是图层排列次序
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()
In [35]:
# Scatter散点图绘制
import matplotlib.pyplot as plt
import numpy as np

n = 1024 # data size
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)  # color value

plt.scatter(X,Y,s=75,c=T,alpha=0.5)

plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
# hide ticks
plt.xticks(())
plt.yticks(())

plt.show()
In [48]:
# Bar柱状图绘制
import matplotlib.pyplot as plt
import numpy as np

n =12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = -(1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

plt.bar(X, Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, Y2, facecolor='#ff9999', edgecolor='white')

plt.ylim(-1.1,1)
plt.xticks(range(12))

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

for x,y in zip(X,Y1):
    # ha means horizontal alignment,va means vertical alignment
    plt.text(x, y+0.04, '%.2f' % y, ha='center', va='bottom')

for x,y in zip(X,Y2):
    # ha means horizontal alignment,va means vertical alignment
    plt.text(x, y-0.04, '%.2f' % y, ha='center', va='top')
In [55]:
# Contours等高线图
import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # the height function
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)

n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
# use plt.contourf to filling contours
# X,Y and value for (X,Y) point
# 8代表等高线的密集程度
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
# use plt.contour to add contour lines
C = plt.contour(X,Y,f(X,Y),8,colors='black')
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())

plt.show()
In [56]:
# 绘制image图像
import matplotlib.pyplot as plt
import numpy as np

a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)

plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')

plt.colorbar(shrink=0.92)

plt.xticks(())
plt.yticks(())
plt.show()
In [63]:
# 3D数据
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
# 添加3D坐标轴
ax = Axes3D(fig)
# X,Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)    # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
# rstride 和 cstride 分别代表 row 和 column 的跨度。
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# 绘制x-y平面的等高线,zdir为投影方向,offset为投影面相对0的偏置
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))

ax.set_zlim(-2,2)

plt.show()
In [78]:
# Subplot多合一显示
# 绘制均匀划分图中图
import matplotlib.pyplot as plt
import numpy as np
import math

plt.figure()
# subplot(row_num,col_num,current_position)
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])

plt.subplot(2,2,2)
plt.plot([0,1],[0,-1])
# subplot(223)是简写
plt.subplot(223)
x = np.linspace(0,20,10)
y = x**2
plt.plot(x,y)

plt.subplot(224)
x = np.linspace(0,20,50)
y = np.sin(x)
plt.plot(x,y)

plt.show()
In [81]:
# 绘制不均匀划分图中图
import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
# subplot(行数,列数,网格位置)
plt.subplot(2,3,4)
plt.plot([0,1],[0,-1])

plt.subplot(2,3,5)
x = np.linspace(0,20,10)
y = x**2
plt.plot(x,y)

plt.subplot(2,3,6)
x = np.linspace(0,20,50)
y = np.sin(x)
plt.plot(x,y)
plt.xticks(())

plt.show()
In [87]:
# subplot的分格显示
# 方法1:subplot2grid
import matplotlib.pyplot as plt

plt.figure()
# (3,3)将窗口划分为3*3网格,(0,0)表示绘图起始点0行0列
# colspan列跨度, rowspan行跨度,默认为1
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax1.plot([1, 2], [1, 2])    # 画小图
ax1.set_title('ax1_title')  # 设置小图的标题

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')

plt.show()
In [88]:
# 方法2:gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure()
# 将窗口划分为3行3列
gs = gridspec.GridSpec(3,3)
'''
使用plt.subplot来作图, gs[0, :]表示这个图占第0行和所有列, gs[1, :2]表示这个图占第1行和第2列前的所
有列, gs[1:, 2]表示这个图占第1行后的所有行和第2列, gs[-1, 0]表示这个图占倒数第1行和第0列,
gs[-1, -2]表示这个图占倒数第1行和倒数第2列.
'''
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
In [97]:
# 图中图绘制
import matplotlib.pyplot as plt

fig = plt.figure()
# 创建数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# 设置图占整个figure的比例
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
# 第一个图中图
left, bottom, width, height = 0.2, 0.55, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
# 第二个图中图
plt.axes([0.63, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()
In [101]:
# 次坐标轴
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,10,0.1)

y1 = 0.05*x**2
y2 = -1*y1
# 获取默认坐标系
fig, ax1 = plt.subplots()
ax2= ax1.twinx()

ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'r-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1',color='g')
ax2.set_ylabel('Y2',color='r')

plt.show()
In [105]:
# 动画绘制(略)
from matplotlib import animation

Comments