欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Matplotlib python 数据可视化

程序员文章站 2022-05-20 19:45:29
...

Matplotlib python 数据可视化


视频链接

1.如何安装matplotlib

系统是基于ubuntu18.04+python3

首先安装pip3

$ sudo apt install python3-pip
$ pip3 install numpy
$ pip3 install matplotlib

2.基本用法

2.1 画函数

画y=2*x+1的曲线在区间[-1,1]上;

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-05 11:16:56
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
## y = 2 * x + 1
y=x**2
plt.plot(x, y)
plt.show()

Matplotlib python 数据可视化

Matplotlib python 数据可视化

2.2画不同的函数在一张图上

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y1)

plt.figure(num=3, figsize=(8, 5),)#注意这里有,不然不显示第二个曲线
plt.plot(x, y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')

plt.show()

Matplotlib python 数据可视化

2.2 设置figure图像

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-06 22:23:53
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))#设置x轴的范围
plt.ylim((-2, 3))#设置y轴的范围
plt.xlabel('I am x')
plt.ylabel('I am y')
#set new sticks
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#set tick labels
plt.yticks([-2,-1.8,-1,-1.22,3],[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
plt.show()

Matplotlib python 数据可视化

2.3 坐标轴的设置

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-06 22:54:26
'''

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))#
plt.ylim((-2, 3))#
plt.xlabel('I am x')
plt.ylabel('I am y')
#set new sticks
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#set tick labels
plt.yticks([-2,-1.8,-1,-1.22,3],[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
#gca='get current axis'
ax = plt.gca()
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))

plt.show()

2.4 legend图例

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 09:45:59
'''

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()

plt.xlim((-1, 2))#
plt.ylim((-2, 3))#

#set new sticks
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
#set tick labels
plt.yticks([-2,-1.8,-1,-1.22,3],[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(loc='best')
#plt.legend(handles=[l1,l2],labels=['up','down'],loc='best')

plt.show()

Matplotlib python 数据可视化

2.5 Annotation标注

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 15:27:28
'''
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 2 * x + 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.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

x0 = 1
y0 = 2 * x0 + 1
plt.plot([x0, x0], [0, y0,], 'k--', linewidth=1.5)
plt.scatter([x0,], [y0,], s=50, color='b')
#annotation
#method 1
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"))
#method 2
plt.text(-3.7, 3, r'$This\ is\ the\ some\ test. \mu\ \sigma_i\ \alpha_t$',
        fontdict={'size':16,'color':'r'})

plt.show()

Matplotlib python 数据可视化

2.6 tick能见度

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 15:44:34
'''
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1 * x 
plt.figure()
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.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)
    label.set_bbox(dict(facecolor='white',edgecolor='none',alpha=0.7,zorder=2))
plt.show()

Matplotlib python 数据可视化

3.画图种类

3.1 散点图

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 15:59:29
'''
import matplotlib.pyplot as plt
import numpy as np
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)  #for color
plt.scatter(X,Y,s=75,c=T,alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(())
plt.ylim(-1.5, 1.5)
plt.yticks(())
plt.show()

Matplotlib python 数据可视化

3.2 柱状图

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 16:23:04
'''
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(12)
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')
for x, y in zip(X, Y1):
    plt.text(x + 0.1, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
    plt.text(x+0.1,-y-0.05,'%.2f'%-y,ha='center',va='top')
plt.xlim(-1, n)
plt.ylim(-1.25,1.25)
plt.show()

Matplotlib python 数据可视化

3.3 等高线

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 16:52:20
'''
import matplotlib.pyplot as plt
import numpy as np
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)

plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)

C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()

Matplotlib python 数据可视化

3.3 Image图片

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 17:08:15
'''
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)

"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)

plt.show()

Matplotlib python 数据可视化

3.4 3D数据

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-09 17:48:00
'''
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure()
ax = Axes3D(fig)

X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='x',offset=-4,cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2,2)

plt.show()

Matplotlib python 数据可视化

4.多图合并显示

4.1 subplot多合一显示

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.subplot(2,2,1)
plt.plot([0, 1], [0, 1])
plt.subplot(222)
plt.plot([0, 1], [0, 2])
plt.subplot(223)
plt.plot([0, 1], [0, 3])
plt.subplot(224)
plt.plot([0, 1], [0, 4])
plt.tight_layout()
plt.show()

Matplotlib python 数据可视化

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.subplot(2,1,1)
plt.plot([0, 1], [0, 1])
plt.subplot(234)
plt.plot([0, 1], [0, 2])
plt.subplot(235)
plt.plot([0, 1], [0, 3])
plt.subplot(236)
plt.plot([0, 1], [0, 4])
plt.tight_layout()
plt.show()

Matplotlib python 数据可视化

4.2 分格显示

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# method 1
plt.figure()
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))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
ax5=plt.subplot2grid((3,3),(2,1))
plt.tight_layout()
plt.show()

Matplotlib python 数据可视化

#method 2
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
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])

plt.tight_layout()
plt.show()

Matplotlib python 数据可视化

f,((ax11,ax12),(ax13,ax14))=plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])
plt.tight_layout()
plt.show()

Matplotlib python 数据可视化

4.3 图中图

'''
@Description: 
@version: 
@Author: sunshine
@Github: https://subshine.github.io/
@Email: aaa@qq.com
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-11 22:33:54
'''
import matplotlib.pyplot as plt

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

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

ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])
ax2.plot(x, y, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')

plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::1], x, 'g') #[::1] data inverse
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()

Matplotlib python 数据可视化

4.3 次坐标轴

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

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


plt.show()

Matplotlib python 数据可视化

4.4 使用animation绘制动画

from matplotlib import pyplot as plt
import numpy as np
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/10.0))  # update the data
    return line,


# Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.sin(x))
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
# blit=True dose not work on Mac, set blit=False
# interval= update frequency
ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
                              interval=20, blit=False)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])  #save video



plt.show()

Matplotlib python 数据可视化

相关标签: 模式识别