Python之Matplotlib可视化基础

1. import导入

import matplotlib.pyplot as plt
import numpy as np

2.基本绘图

plt.plot([1,2,3,4]) # basic plot
plt.ylabel("some num")
plt.show()

plt.plot([1,2,3,4],[1,4,9,16]) # plot x versus y
plt.show()

3. 添加一些样式

# borrowed from Matlab
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20]) # [xmin, xmax, ymin, ymax]
plt.show()

t = np.arange(0.,5.,0.2)
# more style here
# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
plt.plot(t,t,'r--', t,t**2,'bs', t,t**3,'g^')
plt.show()

4. 多重图形和轴

MATLAB和pyplot有当前图形和当前轴的概念。所有绘图命令都应用于当前轴。函数gca()返回当前轴(一个matplotlib.axes)。函数gcf()返回当前图(matplotlib.figure.Figure 图实例)。

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)
t1 = np.arange(0.0,5.0,0.1)
t2 = np.arange(0.0,5.0,0.02)
plt.figure(1)
# The subplot() command specifies numrows, numcols, fignum where fignum ranges from 1 to numrows*numcols
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k');
plt.subplot(212)
plt.plot(t2,np.cos(2*np.pi*t2),'r--');

plt.figure(1)  # the first figure
plt.subplot(211)  # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)  # the second subplot in the first figure
plt.plot([4, 5, 6])

plt.figure(2)  # a second figure
plt.plot([4, 5, 6])  # creates a subplot(111) by default

plt.figure(1)  # figure 1 current; subplot(212) still current
plt.subplot(211)  # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3')

plt.show()

更多关于图和轴的方法:

可以使用clf()清除当前图,使用cla()清除当前轴。

在使用close()显式关闭图形之前,图形所需的内存不会完全释放。

5. 处理文本

text()命令可用于在任意位置添加文本,而xlabel()、ylabel()和title()可用于在指定位置添加文本。

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
 
n, bins, patches = plt.hist(x,50,normed=1,facecolor='g',alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probablity')
plt.title('Histogram of IQ')
plt.text(60,.025,r'$\mu=100,\ \sigma=15$')
plt.axis([40,160,0,0.03])
plt.grid(True)
plt.show()

6. 基本图功能

棘线是连接轴标记和记录数据区域边界的线。它们可以被放置在任意位置,直到现在,它们都在轴线的边界上。我们要改变一下,因为我们想把它们放在中间。因为它们有四个(顶部/底部/左侧/右侧),我们将通过设置它们的颜色为none来放弃顶部和右侧,并将底部和左侧移动到数据空间坐标中的坐标0。

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)

# new figure
plt.figure(figsize=(10, 6), dpi=80)

# add style
plt.plot(X, C, color='blue', linewidth=2.5, linestyle='-', label="cosine")
plt.plot(X, S, color='red', linewidth=2.5, linestyle='-', label="sine")

# setting limits
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)

# setting ticks
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, 1],
           [r'$-1$', r'$0$', r'$+1$'])

# moving spines
ax = plt.gca()  # get current axis
ax.spines['right'].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))

# legend
plt.legend(loc='upper left', frameon=False)

# annotate some points
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5)
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             )

# make label bigger
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(16)
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))

plt.show()

7. 更多类型

常规的绘图

# plt.fill_between(x, y1, y2=0, where=None)
# x : array
#     An N-length array of the x data
# y1 : array
#     An N-length array (or scalar) of the y data
# y2 : array
#     An N-length array (or scalar) of the y data
 
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
 
plt.plot(X,Y+1,color='blue',alpha=1.00)
plt.fill_between(X,1,Y+1,color='blue',alpha=.25) # x, y1, y2
 
plt.plot(X,Y-1,color='blue',alpha=1.00)
plt.fill_between(X,-1,Y-1,(Y-1)>-1,color='blue',alpha=.25) # where condition
plt.fill_between(X,-1,Y-1,(Y-1)<-1,color='red',alpha=.25)
 
plt.xlim(-np.pi,np.pi), plt.xticks([])
plt.ylim(-2.5,2.5), plt.yticks([])
plt.show()
 

散点图

n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)
 
plt.axes([0.025,0.025,0.95,0.95])
plt.scatter(X,Y,c=T,alpha=.5) #color
 
plt.xlim(-2,2), plt.xticks([])
plt.ylim(-2,2), plt.yticks([])
 
plt.show()

条形图

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.axes([0.025,0.025,0.95,0.95])
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
 
# Make an iterator that aggregates elements from each of the iterables.
# Returns an iterator of tuples, where the i-th tuple contains
# the i-th element from each of the argument sequences or iterables.
for x,y in zip(X,Y1):
    plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
 
for x,y in zip(X,-Y2):
    plt.text(x+0.4, y-0.05, '%.2f'%y,ha='center',va='top')
 
plt.xlim([-.5,n]), plt.xticks([])
plt.ylim([-1.25,1.25]), plt.yticks([])
plt.show()

轮廓图

def f(x,y): 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)
# np.meshgrid(*xi, **kwargs), Return coordinate matrices from coordinate vectors.
 
C = plt.contourf(X,Y,f(X,Y),8,alpha=.75,cmap='jet')
C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
plt.clabel(C, inline=1, fontsize=10)
# plt.clabel(CS, *args, **kwargs) Label a contour plot.
 
plt.xticks([]), plt.yticks([])
plt.show()

显示图像

def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 10
x = np.linspace(-3,3,4*n)
y = np.linspace(-3,3,3*n)
X,Y = np.meshgrid(x,y)
Z = f(X,Y)
plt.axes([0.025,0.025,0.95,0.95])
plt.imshow(Z,interpolation='nearest',cmap='bone',origin='lower')
plt.colorbar(shrink=0.9)
plt.xticks([])
plt.yticks([])
plt.show()

Pie Charts

n = 20
Z = np.ones(n)
Z[-1] *= 2
plt.axes([0.025,0.025,0.95,0.95])
plt.pie(Z, explode=Z*.05, colors = ['%f' % (i/float(n)) for i in range(n)])
plt.gca().set_aspect('equal')
plt.xticks([]), plt.yticks([])
plt.show()

向量场图

n = 8
X,Y = np.mgrid[0:n,0:n]
T = np.arctan2(Y-n/2.0,X-n/2.0)
R = 10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
U,V = R*np.cos(T), R*np.sin(T)
plt.axes([0.025,0.025,0.95,0.95])
 
plt.quiver(X,Y,U,V,R,alpha=.5)
plt.quiver(X,Y,U,V,edgecolor='k',facecolor='None',linewidth=0.5)
 
plt.xlim([-1,n]),plt.xticks([])
plt.ylim([-1,n]),plt.yticks([])
plt.show()

网格

ax = plt.axes([0.025,0.025,0.95,0.95])
 
ax.set_xlim(0,4)
ax.set_ylim(0,3)
 
ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
 
ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')
ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')
 
ax.set_xticklabels([]) # diff between set_xticks([])
ax.set_yticklabels([]) # with little vertical lines
 
plt.show()

多块

fig = plt.figure()
fig.subplots_adjust(bottom=0.025,left=0.025,top=0.975,right=0.975)
plt.subplot(2,1,1) # subplots shape (2,1)
plt.xticks([]), plt.yticks([])
 
plt.subplot(2,3,4) # subplots shape(2,3)
plt.xticks([]), plt.yticks([])
 
plt.subplot(2,3,5)
plt.xticks([]), plt.yticks([])
 
plt.subplot(2,3,6)
plt.xticks([]), plt.yticks([])
plt.show()

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值