赞
踩
目录
- import matplotlib.pyplot as plt
- import numpy as np
- # 定义 x 变量的范围 (-3,3) 数量 50
- x=np.linspace(-3,3,50)
- y=x**2
- plt.figure()
- plt.plot(x, y)
- plt.show()
plt.figure(num=None,figsize=None,dpi=None,facecolor=None,edgecolor=None, frameon=True)
- import matplotlib.pyplot as plt
- fig=plt.figure(num="蓝色背景",figsize=(4,3),facecolor="blue")
- plt.show()
- fig=plt.figure(num="红色背景",figsize=(4,3),facecolor="red")
- plt.show()
plt.figure().add_subplot(*)
plt.subplot(*)
plt.figure(**). add_subplot(nrows, ncols, index, **kwargs)plt.figure(**). add_subplot(pos, **kwargs)
- import matplotlib.pyplot as plt
- fig = plt.figure()
- axl = fig.add_subplot(121)
- ax2 = fig.add_subplot(122)
- plt.show()
- import matplotlib.pyplot as plt
- fig = plt.figure()
- axl = fig.add_subplot(121)
- ax2 =fig.add_subplot(122)
- ax2.axis(“off”) #不显示第二个子图
- plt.show()
- import matplotlib.pyplot as plt
- import numpy as np
- fig = plt.figure()
- axl = fig.add_subplot(121)
- ax2 = fig.add_subplot(122)
- plt.plot(np.random.randn(50).cumsum(), 'k--')
- #默认最后一个子图
- plt.show()
图像默认绘制在最后一个子图上面
- import matplotlib.pyplot as plt
- import numpy as np
- fig = plt.figure()
- ax1 = fig.add_subplot(121)
- ax2 = fig.add_subplot(122)
- ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
- ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
- plt.show()
- >>> fig, axes = plt.subplots(2, 3)
- array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fb626374048>,
- <matplotlib.axes._subplots.AxesSubplot object at 0x7fb62625db00>,
- <matplotlib.axes._subplots.AxesSubplot object at 0x7fb6262f6c88>],
- [<matplotlib.axes._subplots.AxesSubplot object at 0x7fb6261a36a0>,
- <matplotlib.axes._subplots.AxesSubplot object at 0x7fb626181860>,
- <matplotlib.axes._subplots.AxesSubplot object at 0x7fb6260fd4e0>]], dtype
- =object)
plt.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, subplot_kw=None, **fig_kw)
参数
| 说明 |
nrows
|
subplot
的行数
|
ncols
|
subplot
的列数
|
sharex
|
所有
subplot
应该使用相同的
X
轴刻度
(
调节
xlim
将会影响所有
subplot)
|
sharey
|
所有
subplot
应该使用相同的
Y
轴刻度
(
调节
ylim
将会影响所有
subplot)
|
subplot_ kw
|
用于创建各
subplot
的关键字字典
|
**fig_ kw
|
创建
figure
时的其他关键字,如
plt.subplots(2,2,figsize=(8,6))
|
plt.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None, hspace=None
- import matplotlib.pyplot as plt
- import numpy as np
- fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
- for i in range(2):
- for j in range(2):
- axes[i, j].hist(np.random.randn(500))
- plt.subplots_adjust(wspace=0.2, hspace= 0)
- plt.show()
plt.plot(x, y, format_string, **kwargs)
可以绘制点和线, 并且对其样式进行控制
tip:当绘制多条曲线时各条曲线的x不能省略
- plt.plot([3,1,2,5,4])
- plt.show()
多个图像
- import numpy as np
- import matplotlib.pyplot as plt
- a=np.arange(10)
- plt.plot(a, a*1.5,a, a*2.5, a*3.5) #横坐标相同
- plt.show()
- import numpy as np
- import matplotlib.pyplot as plt
- x=np.arange(10)
- y1=x*1.5;
- y2=x*2.5;
- y3=x*3.5;
- y4=x*4.5
- plt.figure()
- plt.plot(x,y1,’go-',x,y2,'rx',y3,'*',x,y4,'b-.’)
- plt.show()
函数 | 说明 |
set_title(*)
|
设定图像的标题
|
plt.set_xticks(ticks=None, labels=None)
|
设定
X
轴数据刻度以及标签
|
set_xticklabels(*,*)
|
设定
X
轴刻度的标签
|
set_xlabel(*,*)
|
设定
X
轴的名称
|
plt.set_yticks(ticks=None, labels=None)
|
设定
Y
轴数据刻度以及标签
|
set_yticklabels(*,*)
|
设定
Y
轴刻度的标签
|
set_ylabel(*,*)
|
设定
Y
轴的名称
|
- import matplotlib.pyplot as plt
- import numpy as np
- fig = plt.figure()
- ax = fig.add_subplot(1, 1, 1)
- ax.plot(np.random.randn(1000).cumsum())
- ticks = ax.set_xticks([0, 250, 500, 750, 1000])
- labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],rotation=30,
- fontsize='small')
- ax.set_title('My first matplotlib plot')
- plt.show()
plt.text(x, y, s, fontdict=None, **kwargs)
功能用于将文本添加到数据坐标中x,y位置的轴上。
参数 | 描述 |
x
,
y
:
float
|
放置文本的位置。默认情况下,这是在数据坐标中。
可以使用变换参数来更改坐标系。
|
s
:
str
|
文本。
|
fontdict
:
dict
默认无
|
用于覆盖默认文本属性的字典。如果
fontdict
为
None
则默认值由
rcParams
确定。
|
**
夸克
| 文字属性 |
实例
- import numpy as np
- import matplotlib.pyplot as plt
- t = np.arange(0.0, 2.0, 0.01)
- s = np.sin(2*np.pi*t)
- plt.plot(t, s)
- plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
- plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
- plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',fontsize=20)
- plt.xlabel('time (s)')
- plt.ylabel('volts (mV)')
- plt.show()
tip:图片内部的字体需要掌握一定的Latex语言才可以
plt.arrow(x, y, dx, dy, **kwargs)
- import matplotlib.pyplot as plt
- fig,axes=plt.subplots(3,4)
- axes[0,0].arrow(0,0,1,1)
- axes[0,1].arrow(0,0,1,1,width=0.2,head_width=0.5)
- axes[0,2].arrow(0,0,1,1,width=0.2,head_width=0.5,head_length=0.2)
- axes[0,3].arrow(0,0,1,1,width=0.2,head_width=0.5,head_length=0.2,length_includes_head=True)
- axes[1,0].arrow(0,0,1,1,width=0.2)
- axes[1,1].arrow(0,0,1,1,width=0.2,shape='full')
- axes[1,2].arrow(0,0,1,1,width=0.2,shape='left')
- axes[1,3].arrow(0,0,1,1,width=0.2,shape='right')
- axes[2,0].arrow(0,0,1,1,width=0.2)
- axes[2,1].arrow(0,0,1,1,width=0.2,overhang=0.2)
- axes[2,2].arrow(0,0,1,1,width=0.2)
- axes[2,3].arrow(0,0,1,1,width=0.2,head_starts_at_zero=True)
- plt.show()
- ax=plt.gca()
- # right 、 top 、 bottom 、 left
- ax.spines[‘right’].set_color('none')
- ax.spines['top'].set_color('none')
添加定制图像
matplotlib.axes.Axes.add_patch(p)
- import matplotlib.pyplot as plt
- fig = plt.figure()
- ax = fig.add_subplot(1, 1, 1)
- rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
- circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
- pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],color='g', alpha=0.5)
- ax.add_patch(rect)
- ax.add_patch(circ)
- ax.add_patch(pgon)
- plt.show()
- import matplotlib.pyplot as plt
- import numpy as np
- x=np.arange(0,5,0.02)
- plt.plot(x,np.cos(2*np.pi*x),'r--')
- plt.xlabel('横轴:时间',fontproperties='SimHei',fontsize=15,color='green')
- plt.ylabel('纵轴:振幅',fontproperties='SimHei',fontsize=15)
- plt.title(r'正弦波实例$y=cos(2\pix)$',fontproperties='SimHei',fontsize=25)
- plt.show()
ax.legend([line1, line2, line3], labels=['label1', 'label2’, 'label3'],lloc='lower right', fontsize=12, frameon=True, title=None)
实例
- import matplotlib.pyplot as plt
- import numpy as np
- from numpy.random import randn
- fig = plt.figure()
- ax = fig.add_subplot(1, 1, 1)
- ax.plot(randn(1000).cumsum(), 'k', label='one')
- ax.plot(randn(1000).cumsum(), 'k--', label='two')
- ax.plot(randn(1000).cumsum(), 'k.', label='three')
- ax.legend(labels=["1","2","3"],loc='best')
- plt.show()
plt.subplot(nrows, ncols, plot_number)
在全局绘图区域中创建一个分区体系,并定位到一个子绘图区域。
- import numpy as np
- import matplotlib.pyplot as plt
- x = np.arange(0, 100)
- plt.subplot(221) #作图1
- plt.plot(x, x)
- plt.subplot(222) #作图2
- plt.plot(x, -x)
- plt.subplot(223) #作图3
- plt.plot(x, x ** 2)
- plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)#作图4
- plt.subplot(224)
- plt.plot(x, np.log(x))
- plt.show()
plt.subplot2grid(shape, loc, rowspan, colspan)
- ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
- 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))
- plt.suptitle("subplot2grid")
- import matplotlib.pyplot as plt
- import numpy as np
- import math
- x = np.arange(1,10)
- a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
- a1.plot(x, np.exp(x))
- a1.set_title(‘指数’
- ,fontproperties='SimHei',fontsize=15)
- a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
- a2.plot(x, x*x)
- a2.set_title(‘平方’
- ,fontproperties='SimHei',fontsize=15)
- a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
- a3.plot(x, np.log(x))
- a3.set_title(‘log’)
- plt.tight_layout(); plt.suptitle("subplot2grid")
- plt.show()
plt.savefig() #函数plt.show()之前调用,否则空白
- x = np.arange(1, 11)
- a=plt.plot(x,2*x,x,3*x)
- plt.legend(['a','b'])
- plt.savefig('text.eps',dpi=600)
- plt.show()
plt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None,vmin=None, vmax=None, alpha=None, linewidths=None,verts=None,edgecolors=None, hold=None, data=None, **kwargs)
scatter(x, y, s=None, c=None, marker=None, alpha=None)
- import matplotlib.pyplot as plt
- import numpy as np
- np.random.seed(222)
- x=np.random.rand(20)
- y=np.random.rand(20)
- s = np.array(range(10,110,5))
- c = np.array(range(0,20))
- plt.scatter(x, y,s=s, c=c)
- plt.colorbar()
- plt.show()
plt.colorbar(mappable=None, cax=None, ax=None, **kwarg)
- import matplotlib.pyplot as plt
- fig, axes = plt.subplots(nrows=2, ncols=2)
- for ax in axes.flat:
- im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1)
- plt.colorbar(im, ax=axes.ravel().tolist())
- plt.show()
plt.bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs)
- import matplotlib.pyplot as plt
- import numpy as np
- data_X = ['l1', 'l2', 'l3', 'l4', 'l5']
- data_Y = [0.96332673, 0.41957767, 0.28530194, 0.66399872, 0.39162668]
- data_Y1 = [0.95827706, 0.570968, 0.1820442, 0.6373498, 0.3974183]
- x = np.arange(len(data_X)) # 设定步长
- width = 0.4 # 设置数据条宽度
- fig, ax = plt.subplots()
- p1 = ax.bar(x - width / 2, data_Y, width)
- p2 = ax.bar(x + width / 2, data_Y1, width)
- ax.set_xticks(x)
- ax.set_xticklabels(data_X)
- plt.show()
- import matplotlib.pyplot as plt
- import numpy as np
- data_X = ['l1', 'l2', 'l3', 'l4', 'l5']
- data_Y = [0.96332673, 0.41957767, 0.28530194, 0.66399872, 0.39162668]
- data_Y1 = [0.95827706, 0.570968, 0.1820442, 0.6373498, 0.3974183]
- data_Y2 = [0.52999985, 0.54202189, 0.6418166, 0.69023167, 0.90743048]
- x = np.arange(len(data_X)) # 设定步长
- p1 = plt.bar(x, data_Y )
- p2 = plt.bar(x, data_Y1, bottom=data_Y)#bottom 为数据条距坐标轴的距离
- p3 = plt.bar(x, data_Y2, bottom=[data_Y1[i]+data_Y[i] for i in range(min(len(data_Y1),len(data_Y)))])
- plt.xticks(x, data_X)
- plt.show()
- import matplotlib.pyplot as plt
- import numpy as np
- data_X = ['l1', 'l2', 'l3', 'l4', 'l5']
- data_Y = [0.96332673, 0.41957767, 0.28530194, 0.66399872, 0.39162668]
- data_Y1 = [0.95827706, 0.570968, 0.1820442, 0.6373498, 0.3974183]
- data_Y2 = [0.52999985, 0.54202189, 0.6418166, 0.69023167, 0.90743048]
- x = np.arange(len(data_X)) # 设定步长
- p1 = plt.bar(x, data_Y)
- p2 = plt.bar(x, [-data_Y1[i] for i in range(len(data_Y1))])#将数据取成负数
- plt.xticks(x, data_X)
- plt.show()
- rects1 = ax.bar(index, means_men, bar_width,
- alpha=opacity, color='b',
- yerr=std_men, error_kw=error_config,
- label='Men')
- rects2 = ax.bar(index + bar_width, means_women, bar_width,
- alpha=opacity, color='r',
- yerr=std_women, error_kw=error_config,
- label='Women')
plt.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)
- import numpy as np
- import matplotlib.pyplot as plt
- data_X = ['l1', 'l2', 'l3', 'l4', 'l5']
- data_Y = [0.96332673, 0.41957767, 0.28530194, 0.66399872, 0.39162668]
- plt.barh(data_X, data_Y)
- plt.show()
plt.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid’, orientation='vertical', rwidth=None,log=False, color=None, label=None, stacked=False, normed=None)
- import matplotlib.pyplot as plt
- # matplotlib.axes.Axes.hist() 方法的接口
- n, bins, patches = plt.hist(x=d, bins='auto', color='#0504aa',
- alpha=0.7, rwidth=0.85)
- plt.grid(axis='y', alpha=0.75)
- plt.xlabel('Value')
- plt.ylabel('Frequency')
- plt.title('My Very Own Histogram')
- plt.text(23, 45, r'$\mu=15, b=3$')
- maxfreq = n.max()
- # 设置y轴的上限
- plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6,shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True,wedgeprops=None, textprops=None, center=0, 0, frame=False, rotatelabels=False, *,normalize=None, data=None)
- import matplotlib.pyplot as plt
- plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
- labels = 'A','B','C','D'
- explode = (0,0,0.1,0) #将第三块分离出来
- sizes = [10,10,10,70]
- colors = ['r','g','y','b']
- plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.2f%%',
- pctdistance=0.4,shadow=True,labeldistance=0.8,startangle=30,radius=1.3,
- counterclock=False,textprops={'fontsize':20,'color':'black'})
- plt.title("饼图详解示例")
- plt.text(1,-1.2,'By:Biyoulin')
- plt.legend(loc="upper right",fontsize=10,bbox_to_anchor=(1.1,1.05),borderaxespad=0.3)
- plt.show()
matplotlib errorbar正误差棒
plt.errorbar(x, y, yerr=None, xerr=None, fmt=u'', ecolor=None, elinewidth=None,capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False,xuplims=False, errorevery=1, capthick=None, hold=None, data=None, **kwargs)
- import matplotlib.pyplot as plt
- x = [1, 2, 3, 4, 5]
- y = [1, 2, 1, 2, 1]
- y_errormin = [0, 0, 0, 0, 0]
- y_errormax = [0.2, 0.4, 0.6, 0.4, 0.2]
- x_error = 0.5
- y_error = [y_errormin, y_errormax]
- plt.bar(x, y)
- plt.errorbar(x, y,yerr=y_error,capsize = 8,fmt='o', color="r")
- plt.show()
- import matplotlib.pyplot as plt
- import seaborn as sns
- plt.rcParams['font.sans-serif'] = ['SimHei']
- # Matplotlib中设置字体-黑体,解决Matplotlib中文乱码问题
- plt.rcParams['axes.unicode_minus'] = False
- # 解决Matplotlib坐标轴负号'-'显示为方块的问题
- sns.set(font='SimHei')
- # Seaborn中设置字体-黑体,解决Seaborn中文乱码问题
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。