11-Python 科学计算_绘图篇(matplotlib)

课程概要:
  1、matplotlib库的使用介绍
  2、mpl_toolkits 库的使用介绍
  3、mpl_toolkits 库的使用介绍(二)

1、matplotlib 库的使用介绍

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,1000)
y = np.sin(x)
z = np.cos(x)
#   配置
plt.figure(figsize=(8,4))       #   框的大小
plt.plot(x,y,label='$sin(x)$')
plt.plot(x,z,'b--',label='$cos(x)$')        #   蓝色虚线
plt.xlabel("Time(s)")
plt.ylabel("")
plt.title("matplotlib")
plt.ylim(-1.2, 1.2)
plt.legend()                        #   显示为一个样式
plt.show()

fig = plt.gcf()                         #   获得当前图标的对象
ax = plt.gca()                      #   获得子图的对象
print fig
print ax
 
>>> 
Figure(640x480)
Axes(0.125,0.1;0.775x0.8)

多轴绘图

#   多轴绘图
#   subplot(numRows, numCols, plotNum)

import matplotlib.pyplot as plt

for idx, color in enumerate("rgbyck"):
    plt.subplot(320+idx+1, axisbg=color)

plt.show()
import numpy as np
import matplotlib.pyplot as plt

w = np.linspace(0.1, 1000, 1000)
p = np.abs(1/(1+0.1j*w))

plt.subplot(221)
plt.plot(w, p, linewidth=2)     #   算术坐标系
plt.ylim(0, 1.5)

plt.subplot(222)
plt.semilogx(w, p, linewidth=2)     #   x 对数坐标系
plt.ylim(0, 1.5)

plt.subplot(223)
plt.semilogy(w, p, linewidth=2)     #   y 对数坐标系
plt.ylim(0, 1.5)

plt.subplot(224)
plt.loglog(w, p, linewidth=2)           #   对数坐标系
plt.ylim(0, 1.5)

plt.show()
#   1.txt的文本
>>> data
array([[  0.,  10.,  20.,  30.,  40.],
       [ 10.,  23.,  33.,  43.,  53.],
       [ 20.,  83.,  23.,  55.,  33.],
       [ 30.,  93.,  44.,  22.,  55.],
       [ 40.,  72.,  33.,  44.,  66.]])
import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt(r"D:\1.txt")
width = (data[1, 0] - data[0, 0])*0.4       #   柱形的宽带为4

#   data[:, 0]:所有行数据
#   data[:, 1]:所有列数据    
plt.figure()                        
plt.bar(data[:, 0] - width, data[:, 1], width, label='person')  
plt.xlim(-width, 40)                        #   x 的取值区间
plt.xlabel("Age")
plt.ylabel("Num")

plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt

plt.figure()
x = np.random.rand(100)
y = np.random.rand(100) 
#   marker:绘制点的形状和大小,5代表五边形,1是大小        
#      s的默认值是20
plt.scatter(x, y, s=x*1000, c=y, marker=(5,1), lw=2, facecolor='none')  
#   marker:绘制点的形状和大小    lw:linewidth    facecolor:颜色
plt.xlim(0, 1)  #  c:cmap不是color,cmap绘制出来是彩图(不同颜色)
plt.ylim(0, 1)

plt.show()

2、mpl_toolkits 库使用介绍(一)

3D图

#   3D图     
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')       #   projection='3d' 已经隐性调用了Axes3D

#   ax = Axes3D(fig)            #   可以加上也可以不加
th = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(th)
y = r * np.cos(th)

ax.plot(x, y, z, label='hello')     #   立体的
ax.legend()
plt.show()
ax.plot(x, y, label='hello')        #   平面的
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D 

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)

    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

轮廓图

#   轮廓图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X, Y, Z = axes3d.get_test_data(0.05)        #   生成一系列的测试数据
cset = ax.contour(X, Y, Z,cmap=cm.coolwarm) #   contour:生成轮廓图
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
#   修改
cset = ax.contour(X, Y, Z,extend3d=True, cmap=cm.coolwarm)      #   颜色的填充

3、mpl_toolkits 库使用介绍(二)

3D柱形图

#   3D柱形图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for c, z in zip(['r', 'g', 'b', 'y'], (30, 20, 10, 0)):
    x = np.arange(20)
    y = np.random.rand(20)
    cs = [c] * len(x)
    cs[0] = 'c'
    ax.bar(x, y, zs=z, zdir='y', color = cs)

ax.set_xlabel('x')

plt.show()

绘制曲面

#   绘制曲面

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')

绘制文字

#   绘制文字

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')

zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10,3, 8, 9, 1, 8)

for zdir, x, y, z in zip(zdirs, xs, ys, zs):
    label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)
    ax.text(x, y, z, label, zdir)

ax.text(9, 0, 0, 'red', color='red')
ax.text2D(0.05, 0.95, "20 text", transform=ax.transAxes)

ax.set_xlim3d(0,10)
ax.set_ylim3d(0,10)
ax.set_zlim3d(0,10)

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
    原文作者:LuCh1Monster
    原文地址: https://www.jianshu.com/p/7f97278df54d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞