Python-matplotlib画图(学习笔记)

Matplotlib是什么?

Matplotlib是一个python的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。通过Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

简单的使用
import  matplotlib.pyplot as plt
squares=[1,2,3,4,5]
plt.plot(squares)

plt.show()

运行结果:
在这里插入图片描述
注意:
1.如果不使用plo.show()图表是显示不出来的,因为可能你要对图表进行多种的描述,所以通过显式的调用show()可以避免不必要的错误。

Figure对象

我这里单拿出一个一个的对象,然后后面在进行总结。在matplotlib中,整个图表为一个figure对象。其实对于每一个弹出的小窗口就是一个Figure对象,那么如何在一个代码中创建多个Figure对象,也就是多个小窗口呢?
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs)
(1)num:这个参数是一个可选参数,即可以给参数也可以不给参数。可以将该num理解为窗口的属性id,即该窗口的身份标识。
如果不提供该参数,则创建窗口的时候该参数会自增,如果提供的话则该窗口会以该num为Id存在。
(2)figsize:可选参数。整数元组,默认是无。
提供整数元组则会以该元组为长宽,若不提供,默认为 rc fiuguer.figsize
例如(4,4)即以长4英寸 宽4英寸的大小创建一个窗口
(3)dpi:可选参数,整数。表示该窗口的分辨率,如果没有提供则默认为 figure.dpi
(4)facecolor:可选参数,表示窗口的背景颜色,如果没有提供则默认为figure.facecolor
其中颜色的设置是通过RGB,范围是’#000000’~’#FFFFFF’,其中每2个字节16位表示RGB的0-255
例如’#FF0000’表示R:255 G:0 B:0 即红色。
(5)edgecolor:可选参数,表示窗口的边框颜色,如果没有提供则默认为figure,edgecolor
(6)frameon:可选参数,表示是否绘制窗口的图框,默认是
(7)figureclass:暂不了解
(8)clear:可选参数,默认是false,如果提供参数为ture,并且该窗口存在的话 则该窗口内容会被清除。

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-1,1,100)
y1=x**2
y2=x*2
#这是第一个figure对象,下面的数据都会在第一个figure中显示
plt.figure()
plt.plot(x,y1)
#这里是第二个figure对象,下面的数据都会在第二个figure中显示
plt.figure(num=3,figsize=(10,5))
plt.plot(x,y2,color='red',linewidth='3.0',linestyle='--')
plt.show()

在这里插入图片描述
这里需要注意的是:

  • 我们看上面的每个图像的窗口,可以看出figure并没有从1开始然后到2,这是因为我们在创建第二个figure对象的时候,指定了一个num = 3的参数,所以第二个窗口标题上显示的figure3。
  • 对于每一个窗口,我们也可以对他们分别去指定窗口的大小。也就是figsize参数。
  • 若我们想让他们的线有所区别,我们可以用下面语句进行修改
plt.plot(x,y2,color = 'red',linewidth = 3.0,linestyle = '--')
numpy.linspace使用详解

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
在指定的间隔内返回均匀间隔的数字。
返回num均匀分布的样本,在[start, stop]。
这个区间的端点可以任意的被排除在外。
了解更多.

设置坐标轴

  • 更改在图表上显示x,y的取值范围
  • 给横纵坐标设置名称
  • 把坐标轴换成不同的单位
import matplotlib.pyplot as plt
import numpy as np
import math

x = np.linspace(-1,2,5)#生成-1到2并且个数为5的一组点(以队列的形式)
plt.xticks(x)#以生成的横坐标作为描点
y=2*x
#在对应坐标处更换名称
plt.yticks([-2,-1,0,1,2],['really bad','b','c','d','good'])
plt.xlim(-1,2)#截取0-1的x轴
plt.ylim(-2)#从y=0开始截取y轴
plt.xlabel("x")#设置x轴名称
plt.ylabel("y")
plt.plot(x,y,color="#faf",linewidth=4,linestyle='-')#设置函数线条的颜色,粗细和风格
plt.show()

运行截图
在这里插入图片描述

legend图例

我们很多时候会再一个figures中去添加多条线,那我们如何去区分多条线呢?这里就用到了legend。
plt.legend(handles = [l1,l2],labels = [‘up’,‘down’],loc = ‘best’,shodow=True)
一旦在legend()函数中使用了labels属性,那么之前在plot函数中设置的label就会失效。如果labels中设置的参数比handels的参数少,那么labels中有多少个参数就会在图例中显示多少个函数信息。
plot函数石油返回值的,若想用legend函数的handles属性,必须在接收plot函数的返回值是加上一个‘,’。
loc表示图例的显示位置,默认显示位置为‘best’,即以最好的方式显示在图片中,尽量少的遮挡函数。

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(0,4,50)
y1=2*x
y2=4*x

# 简单的使用
l1, = plt.plot(x, y1, label='linear line')#注意','很重要
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')

# 简单的设置legend(设置位置)
#方式一
plt.legend(loc='center')#(lower,center,upper)和(left,center,right)之间进行组合,还有特殊的‘center'指位于图中间,'best'表示放在遮住数据最少的位置
#方式二
plt.legend(loc="best",handles =[l1,l2],labels=["line1","line2"],shadow=True)
plt.show()

运行截图
在这里插入图片描述

在图片上加一些标注annotation(注解)

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')
print("----重新设置x轴和y轴-------")
# 将底下的作为x轴
ax.xaxis.set_ticks_position('bottom')
# 并且data,以x轴的数据为基本
ax.spines['bottom'].set_position(('data', 0))

# 将左边的作为y轴
ax.yaxis.set_ticks_position('left')
# 并且data,以y轴的数据为基本
ax.spines['left'].set_position(('data', 0))

print("------- 注解方式一 -----------")
x0 = 1
y0 = 2 * x0 + 1

plt.plot([x0, x0], [0, y0], "k--", linewidth=2.5, color='red')
plt.plot([0, x0], [y0, y0], 'k--', linewidth=2.5, color='red')
plt.scatter([x0], [y0], s=50, color='b')
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.show()

注意:

  • xy就是需要进行注释的点的横纵坐标;
  • xycoords = 'data’说明的是要注释点的xy的坐标是以横纵坐标轴为基准的;
  • xytext=(+30,-30)和textcoords='data’说明了这里的文字是基于标注的点的x坐标的偏移+30以及标注点y坐标-30位置,就是我们要进行注释文字的位置;
  • fontsize = 16就说明字体的大小;
  • arrowprops = dict()这个是对于这个箭头的描述,arrowstyle=’->'这个是箭头的类型,connectionstyle="arc3,rad=.2"这两个是描述我们的箭头的弧度以及角度的。
    第一种添加标签
    在这里插入图片描述
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"))

第二种添加标签
在这里插入图片描述

print("-----方式二-----")
plt.text(-3.7,3,r'$this\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={
    
    'size':16,'color':'r'})

画图的种类

scatter散点图
import matplotlib.pyplot as plt
import numpy as np

# 数据个数
n = 24

# 用np.random.normal生成随机数,返回 列表。其中参数为 平均数是0,方差是1,生成n个数
X = np.random.normal(0, 1, n)
# 用np.random.normal生成随机数,返回 列表。其中参数为 平均数是0,方差是1,生成n个数
Y = np.random.normal(0, 1, n)


# T代表点的颜色
T = np.arctan2(Y, X)  # for color value
np.arctan2(X, Y)

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

# plt.scatter(np.arange(5), np.arange(5))
# plt.xlim(-1.5,1.5)
# plt.ylim(-1.5,1.5)

# 将x轴y轴的下标设为空
plt.xticks([])
plt.yticks(())

plt.show()

在这里插入图片描述

柱状图
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, 0.6, None, facecolor="#9999ff", edgecolor='white')
plt.bar(X, -Y2, 0.6, None, facecolor='#ff9999', edgecolor='white')
# ha:horizontal alignment  水平对齐
# va:Vertical alignment 垂直对齐
for x, y in zip(X, Y1):
    plt.text(x, y + 0.01, '%.2f' % y, ha='center', va='bottom', fontdict={'size': 10, 'color': "red"})
for x, y in zip(X, Y2):
    plt.text(x, -y - 0.01, '%.2f' % y, ha='center', va='top')

plt.show()

在这里插入图片描述

Contours等高线图
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绑定成网格的输入值
X, Y = np.meshgrid(x, y)
# 把颜色放入等高线内
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)

# 画等高线的线
C = plt.contour(X, Y, f(X, Y), 8, alpha=1, colors='green', linewidths=0.5)

# 给等高线加上label描述
plt.clabel(C, inline=True, fontsize=10, colors='black')
plt.show()

在这里插入图片描述

image图片
import matplotlib.pyplot as plt
import numpy as np
import random

list1 = []
for i in range(9):
    list1.append(random.random())

print(list1)
print(type(list1))

list1 = np.random.normal(0, 1, 9)
print(type(list1))
# a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
#               0.365348418405, 0.439599930621, 0.525083754405,
#               0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)
a = np.array(list1).reshape(3, 3)
print(a)
print(type(a))
plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
# 显示colorbar,shrink表示压缩为图片的长的多少
plt.colorbar(shrink=0.7)
plt.xticks(())
plt.yticks(())
plt.show()

在这里插入图片描述
了解更多关于 cmap.

3D数据
import matplotlib.pyplot as plt
import numpy as np
# 画3D图必须引入的包
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = Axes3D(fig)
# 取得X,Y的值
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.cos(R)
# 画出3D图,rstride表示横坐标跨度,cstride表示纵坐标跨度
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_zlim3d(-2, 2)
plt.show()

在这里插入图片描述

多图合并展示

使用subplot函数

多合一显示

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# ax=plt.gca()
# #右边的脊梁
# ax.spines['right'].set_color('none')
# ax.spines['top'].set_color('none')
# print("----重新设置x轴和y轴-------")
# # 将底下的作为x轴
# ax.xaxis.set_ticks_position('bottom')
# # 以y轴的数据为基本,设置‘bottom’脊梁的位置
# ax.spines['bottom'].set_position(('data', 0.5))#axes定义百分比位置
#
# # 将左边的作为y轴
# ax.yaxis.set_ticks_position('left')
# # 以x轴的数据为基本,设置‘left’脊梁的位置
# ax.spines['left'].set_position(('data', 0.5))


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

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

plt.subplot(2, 3, 6)
plt.plot([0, 4], [0, 4])
plt.show()

在这里插入图片描述
Subplot 分隔显示

import matplotlib.pyplot as plt
import numpy as np
#第二种分隔显示需要导入的模块
import matplotlib.gridspec as gridspec

#方法一:subplot2.grid
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
#ax1.set_title()==plt.title()类似的都用set_
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))

#方法二: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])

#方法三:easy to define structure

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

在这里插入图片描述
图中图

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, height = 0.15, 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.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'g')

plt.axes([.6, .2, .25, .25])
# y[::-1]将y中数据进行逆序
plt.plot(y[::-1], x, 'b')

plt.show()

在这里插入图片描述
次坐标轴

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = 0.05 * x ** 2

y2 = -1 * y1
fg, 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", color='g')

ax2.set_ylabel("Y2", color='b')

plt.show()

在这里插入图片描述
animation动画

import matplotlib.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 animation1(i):
    global line
    line.set_ydata(np.sin(x + i / 150 * np.pi * 2))
    return line


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


ani = animation.FuncAnimation(fig=fig, func=animation1, frames=150, init_func=init1, interval=20, blit=False)

plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44788518/article/details/108922841