Matplotlib 数据可视化-网易云课堂笔记

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.plot(x, y)
# plt.show()
[]

figure

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

plt.figure()
plt.plot(x, y1)

plt.figure()
plt.plot(x, y2)

plt.show()

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

plt.figure()
plt.plot(x, y1)

plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
plt.plot(x, y2)

plt.show()

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

plt.figure()
plt.plot(x, y1)

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=5.0, linestyle='--')

plt.show()

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=5.0, linestyle='--')

plt.xlim((-1,1)) # x取值范围
plt.ylim((-1,3))
plt.xlabel("I am x")
plt.ylabel("I am y")
# x轴坐标
x_ticks = np.linspace(-1, 1, 5)
print(x_ticks)
plt.xticks(x_ticks)
# 数学形式alpha 字体美化
plt.yticks([-1, 0, 1, 2, 3], [r'$a\ \alpha$', r'$b\ \beta$', '$\phi\ normal$', 'bad', '$very\ good$'])

plt.show()
[-1.  -0.5  0.   0.5  1. ]

gca get current axis [ˈæksɪs] 轴

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')
plt.show()

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
plt.plot(x, y2)
plt.plot(x, y1, color='black', linewidth=1.0, linestyle='-')

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')

# 改变坐标轴位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.show()

加图例

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
plt.plot(x, y2, label='up')
plt.plot(x, y1, color='black', linewidth=1.0, linestyle='-', label='down')
plt.legend(loc='upper left')

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')

# 改变坐标轴位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.show()

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
l1, = plt.plot(x, y2)
l2, = plt.plot(x, y1, color='black', linewidth=1.0, linestyle='-')
plt.legend(handles=[l1, l2,], labels=['up', 'down'], loc='upper left')

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')

# 改变坐标轴位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.show()

annotation 注解

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
l1, = plt.plot(x, y2)
l2, = plt.plot(x, y1, color='black', linewidth=1.0, linestyle='-')
plt.legend(handles=[l1, l2,], labels=['up', 'down'], loc='upper left')

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')

# 改变坐标轴位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

x0 = 0.5
y0 = 2*x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)

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'))

plt.text(-1.3, 2, r'$This\ is\ the\ some\ text.\ \mu \sigma_i\ \alpha_t$', 
        fontdict={'size':16, 'color':'r'})
# plt.show()
Text(-1.3,2,'$This\\ is\\ the\\ some\\ text.\\ \\mu \\sigma_i\\ \\alpha_t$')

tick 坐标轴下标透明

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

# 一个figure中两条线
plt.figure(num=8, figsize=(8, 5)) # 长8 宽5
l1, = plt.plot(x, y2)
l2, = plt.plot(x, y1, color='black', linewidth=1.0, linestyle='-')
plt.legend(handles=[l1, l2,], labels=['up', 'down'], loc='upper left')

ax = plt.gca()
# 去掉右和上坐标
ax.spines['right'].set_color('none') # spines 脊椎
ax.spines['top'].set_color('none')

# 改变坐标轴位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

x0 = 0.5
y0 = 2*x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)

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'))

plt.text(-1.3, 2, r'$This\ is\ the\ some\ text.\ \mu \sigma_i\ \alpha_t$', 
        fontdict={'size':16, 'color':'r'})

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='b', edgecolor='None', alpha=0.7))

scatter 散点图

n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y) # for color value
print(T[:5])
plt.scatter(X,Y,s=75,c=T,alpha=0.5)


# limit
plt.xlim((-2, 2))
plt.ylim((-2, 2))
# 去掉坐标轴
plt.xticks(())
plt.yticks(())
[ 2.74263839  0.08512228 -2.4040253  -1.08537861  2.92648415]





([], )

bar 柱状图

n = 12
X = np.arange(n)
Y = np.arange(1,n+1)
Y1 = np.random.randint(n, size=n)
plt.bar(X, Y, facecolor='#9999ff')
plt.bar(X, -Y1)

# 用zip才可以获取到x,y两个值
for x, y in zip(X, Y):
    # ha horizontal alignment 水平线向,水平校准 水平对齐方式
    plt.text(x, y+0.05, '%i'%y, ha='center', va='bottom')

for x, y in zip(X, Y1):
    # ha horizontal alignment 水平线向,水平校准 水平对齐方式
    plt.text(x, -y-0.05, '-%.2f'%y, ha='center', va='top')
    
# 去掉坐标轴
plt.xticks(())
plt.yticks(())

# horizontal alignment 水平线向,水平校准 水平对齐方式
([], )

contours 等高线图

# 返回高度
def f(x, y):
    return (1-x/2 + x**5 + y**3) * np.exp(-x**2-y**2)

# 分别生成x y -3到3 256个点
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)

# 定义网格输入值
X, Y = np.meshgrid(x, y)

# 画等高线图 8表示划分为8个区域
plt.contourf(X, Y, f(X, Y), 8, alpha=0.7, cmap=plt.cm.hot)

# 画等高线的线 8表示划分为8个区域
C = plt.contour(X, Y, f(X, Y), 8, colors='black')

# add label
plt.clabel(C, inline=True, fontsize=10)

# 去掉坐标轴
plt.xticks(())
plt.yticks(())
([], )

打印图片 Image

a = np.array([1,2,3,
             4,5,6,
             7,8,9]).reshape(3,3)

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

# colorbar 颜色标注
plt.colorbar(shrink=0.9) #shrink 缩小为原来的90%

# 去掉坐标轴
plt.xticks(())
plt.yticks(())
([], )

3D图

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
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)

# height value
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# rstride 行跨度
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))

ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2, 2)
(-2, 2)

subplot 多合一显示

plt.figure()
plt.subplot(2, 2, 1)
plt.plot([0,1], [0,1])

plt.subplot(2, 2, 2)
plt.plot([0,1], [0,2])

plt.subplot(223)
plt.plot([0,1], [0,2])

plt.subplot(224)
plt.plot([0,1], [0,2])
[]

plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0,1], [0,1])

# 从第四个开始
plt.subplot(2, 3, 4)
plt.plot([0,1], [0,2])

plt.subplot(235)
plt.plot([0,1], [0,2])

plt.subplot(236)
plt.plot([0,1], [0,2])
[]

分格显示 方法1

plt.figure()
# 3行3列 从(0,0)开始
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=1)
ax1.plot([0,1],[0,1])
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))

分格显示 方法2

import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])

分格显示 方法3

f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[2,1])

图中图

fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,5,2,4,9,8]

left, bottom, width, height = 0.1,0.1,0.8,0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x,y,'red')

ax1.set_xlabel('x')
ax1.set_xlabel('y')
ax1.set_title('title 1')

left, bottom, width, height = 0.2,0.6,0.25,0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(x,y,'b')

ax2.set_xlabel('x')
ax2.set_xlabel('y')
ax2.set_title('title 2')

left, bottom, width, height = 0.6,0.2,0.25,0.25
ax3 = fig.add_axes([left, bottom, width, height])
ax3.plot(y[::1],x,'g')

ax3.set_xlabel('x')
ax3.set_xlabel('y')
ax3.set_title('title 3')
Text(0.5,1,'title 3')

次坐标轴

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, 'b--')

ax1.set_label('X data')
ax1.set_ylabel('Y1', color='g')
ax2.set_ylabel('Y1', color='g')

Text(0,0.5,'Y1')

Animation 动画

from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0.2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/100))
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False)

270*12,25*365
(3240, 9125)
123%10
3
i=123
print(str(i)[::-1])
321
l = ["flower","flow","flight"]
for s in zip(*l):
    print(s)
('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'i')
('w', 'w', 'g')
print(*l)
flower flow flight
print(not l)
False
l = []
print(not l)
True

你可能感兴趣的:(Python)