导航:首页 > 编程语言 > pythonaxannotate

pythonaxannotate

发布时间:2022-08-08 13:52:50

python matplotlib 绘制带有刻度的箭头

#绘制箭头例子

def arrow():

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.style.use('seaborn-deep')


fig = plt.figure(figsize=(16, 9),dpi=75)


ax = fig.add_subplot(121)

x=np.array([1,2,3,4])

y=np.array([2,4,6,8])

ax.plot(x,y,color = 'b')

ax.annotate("",

xy=(4.5, 9),

xytext=(4, 8),

arrowprops=dict(arrowstyle="->", color="r"))

# 设置X轴、Y轴最大坐标

ax.set_xlim(0, 10)

ax.set_ylim(0, 10)

ax.grid()

ax.set_aspect('equal')

plt.title("趋势展示图")

plt.show()


arrow()

⑵ python 变量的命名

createPlot.ax1 是表示: ax1 是函数 createPlot 的一个属性,这个可以在函数里面定义也可以在函数定义后加入也可以
example:
def fun():
fun.x =1
当你在python的命令窗口下,运行一次fun()后,x 就是 fun()的一个属性,你在命令窗口下输入
fun.x 后面会显示 1

也可以 在 函数定义完后加入 属性 如 fun.y = 2,在使用 dir(fun),你就会发现fun有 x,y 这两个属性

⑶ python多维数据怎么绘制散点图

python matplotlib模块,是扩展的MATLAB的一个绘图工具库。他可以绘制各种图形,可是最近最的一个小程序,得到一些三维的数据点图,就学习了下python中的matplotlib模块,如何绘制三维图形。

初学者,可能对这些第三方库安装有一定的小问题,对于一些安装第三方库经验较少的朋友,建议使用 Anaconda ,集成了很多第三库,基本满足大家的需求,下载地址,对应选择python 2.7 或是 3.5 的就可以了(PS:后面的demo是python2.7):

首先提醒注意,以下两个函数的区别:

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow') #绘面1

ax.scatter(x[1000:4000],y[1000:4000],z[1000:4000],c='r') #绘点1

1、绘制3D曲面图

# -*- coding: utf-8 -*-"""
Created on Thu Sep 24 16:17:13 2015

@author: Eddy_zheng
"""from matplotlib import pyplot as pltimport numpy as npfrom 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)# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')

plt.show()

效果展示:

2、绘制三维的散点图(通常用于表述一些数据点分布)

4a.mat 数据地址,找到4a.mat 下载即可:

# -*- coding: utf-8 -*-"""
Created on Thu Sep 24 16:37:21 2015

@author: Eddy_zheng
"""import scipy.io as sio
from mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt

mat1 = '4a.mat' #这是存放数据点的文件,需要它才可以画出来。上面有下载地址data = sio.loadmat(mat1)
m = data['data']

x,y,z = m[0],m[1],m[2]
ax=plt.subplot(111,projection='3d') #创建一个三维的绘图工程#将数据点分成三部分画,在颜色上有区分度ax.scatter(x[:1000],y[:1000],z[:1000],c='y') #绘制数据点ax.scatter(x[1000:4000],y[1000:4000],z[1000:4000],c='r')
ax.scatter(x[4000:],y[4000:],z[4000:],c='g')

ax.set_zlabel('Z') #坐标轴ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()24252627

效果:

上面就是学习区分了下两个函数,当时还被小困惑了下,希望对大家有所帮助。其实里面还有好多参数设置,比如说改变颜色,包括绘制点图的点的形状等都是可以改变的,有需要的大家可以自己看看这个函数,学习下(help(对应的function))。

版权声明:本文为博主原创文章,未经博主允许不得转载。Eddy_zheng

⑷ python怎么表示指数

其中有两个非常漂亮的指数函数图就是用python的matplotlib画出来的。这一期,我们将要介绍如何利用python绘制出如下指数函数。

图 1 a>1图 1 a>1

我们知道当0 ,指数函数 是单调递减的,当a>1 时,指数函数是单调递增的。所以我们首先要定义出指数函数,将a值做不同初始化

import math
...
def exponential_func(x, a): #定义指数函数
y=math.pow(a, x)
return y

然后,利用numpy构造出自变量,利用上面定义的指数函数来计算出因变量

X=np.linspace(-4, 4, 40) #构造自变量组
Y=[exponential_func(x) for x in X] #求函数值

有了自变量和因变量的一些散点,那么就可以模拟我们平时画函数操作——描点绘图,利用下面代码就可以实现

import math
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist #导入坐标轴加工模块
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

fig=plt.figure(figsize=(6,4)) #新建画布
ax=axisartist.Subplot(fig,111) #使用axisartist.Subplot方法创建一个绘图区对象ax
fig.add_axes(ax) #将绘图区对象添加到画布中

def exponential_func(x, a=2): #定义指数函数
y=math.pow(a, x)
return y

X=np.linspace(-4, 4, 40) #构造自变量组
Y=[exponential_func(x) for x in X] #求函数值
ax.plot(X, Y) #绘制指数函数
plt.show()

图 2 a=2

图2虽简单,但麻雀虽小五脏俱全,指数函数该有都有,接下来是如何让其看起来像我们在作图纸上面画的那么美观,这里重点介绍axisartist 坐标轴加工类,在的时候我们已经用过了,这里就不再多说了。我们只需要在上面代码后面加上一些代码来将坐标轴好好打扮一番。

图 3 a>1 完整代码# -*- coding: utf-8 -*-图 3 a>1 完整代码# -*- coding: utf-8 -*-"""Created on Sun Feb 16 10:19:23 2020project name:@author: 帅帅de三叔"""import mathimport numpy as npimport matplotlib.pyplot as pltimport mp

⑸ python的Matplotlib如何对每个点进行标记注释

用annotate函数

⑹ python中ax.legend 语句什么意思

legend代表是 图例 ax.legend是图片中 图例的设置

⑺ 在python 中打开波形文件 ︰ 未知的格式 ︰ 49.究竟怎么了

投票
2
回答
1K
查看
我尝试打开波形文件与 wave模块,但是老是同样的错误我试着不管。 包含错误的行是以下 ︰
wav = wave.open(f)

这是错误消息 ︰
Traceback (most recent call last):
File "annotate.py", line 47, in <mole>
play(file)
File "annotate.py", line 33, in play
wav = wave.open(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 498, in open
return Wave_read(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 163, in __init__
self.initfp(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 143, in initfp
self._read_fmt_chunk(chunk)
File "C:\Program Files (x86)\Python\lib\wave.py", line 269, in _read_fmt_chunk
raise Error('unknown format: %r' % (wFormatTag,))
wave.Error: unknown format: 49

字符串 f是路径。WAV 文件,它工作在任何我的媒体播放器播放时。 我当然导入 wave的模块。 我试过 f,作为一个相对和绝对路径。 我试着用"wav"取代"WAV"。
错误什么导致的?
投票
Python 的波模块工作与特定类型的 WAV: PCM (WAVE_FORMAT_PCM: 0x0001)。
在您的情况下,您使用 WAV 类型 WAVE_FORMAT_GSM610[0x0031 = hex(49)].
你可以使用像大胆或者一些程序转换的编解码器,WAV 文件的类型更改为 lib。

⑻ 如何用Python 和牛顿法解四元一次方程组

比较弱的问一下,你确定不是
'''
theta22=spy.Symbol('theta22')
theta33=spy.Symbol('theta33')
theta44=spy.Symbol('theta44')
theta55=spy.Symbol('theta55')
'''
这段有问题?
多了引号?或者。。

⑼ 哪本python书立有蚁群算法

简介

蚁群算法(ant colony optimization, ACO),又称蚂蚁算法,是一种用来在图中寻找优化路径的机率型算法。它由Marco Dorigo于1992年在他的博士论文中提出,其灵感来源于蚂蚁在寻找食物过程中发现路径的行为。蚁群算法是一种模拟进化算法,初步的研究表明该算法具有许多优良的性质。针对PID控制器参数优化设计问题,将蚁群算法设计的结果与遗传算法设计的结果进行了比较,数值仿真结果表明,蚁群算法具有一种新的模拟进化优化方法的有效性和应用价值。
定义

各个蚂蚁在没有事先告诉他们食物在什么地方的前提下开始寻找食物。当一只找到食物以后,它会向环境释放一种挥发性分泌物pheromone (称为信息素,该物质随着时间的推移会逐渐挥发消失,信息素浓度的大小表征路径的远近)来实现的,吸引其他的蚂蚁过来,这样越来越多的蚂蚁会找到食物。有些蚂蚁并没有像其它蚂蚁一样总重复同样的路,他们会另辟蹊径,如果另开辟的道路比原来的其他道路更短,那么,渐渐地,更多的蚂蚁被吸引到这条较短的路上来。最后,经过一段时间运行,可能会出现一条最短的路径被大多数蚂蚁重复着。

解决的问题

三维地形中,给出起点和重点,找到其最优路径。

程序代码:

numpy as npimport matplotlib.pyplot as plt%pylabcoordinates = np.array([[565.0,575.0],[25.0,185.0],[345.0,750.0],[945.0,685.0],[845.0,655.0],[880.0,660.0],[25.0,230.0],[525.0,1000.0],[580.0,1175.0],[650.0,1130.0],[1605.0,620.0],[1220.0,580.0],[1465.0,200.0],[1530.0, 5.0],[845.0,680.0],[725.0,370.0],[145.0,665.0],[415.0,635.0],[510.0,875.0],[560.0,365.0],[300.0,465.0],[520.0,585.0],[480.0,415.0],[835.0,625.0],[975.0,580.0],[1215.0,245.0],[1320.0,315.0],[1250.0,400.0],[660.0,180.0],[410.0,250.0],[420.0,555.0],[575.0,665.0],[1150.0,1160.0],[700.0,580.0],[685.0,595.0],[685.0,610.0],[770.0,610.0],[795.0,645.0],[720.0,635.0],[760.0,650.0],[475.0,960.0],[95.0,260.0],[875.0,920.0],[700.0,500.0],[555.0,815.0],[830.0,485.0],[1170.0, 65.0],[830.0,610.0],[605.0,625.0],[595.0,360.0],[1340.0,725.0],[1740.0,245.0]])def getdistmat(coordinates):num = coordinates.shape[0]distmat = np.zeros((52,52))for i in range(num):for j in range(i,num):distmat[i][j] = distmat[j][i]=np.linalg.norm(coordinates[i]-coordinates[j])return distmatdistmat = getdistmat(coordinates)numant = 40 #蚂蚁个数numcity = coordinates.shape[0] #城市个数alpha = 1 #信息素重要程度因子beta = 5 #启发函数重要程度因子rho = 0.1 #信息素的挥发速度Q = 1iter = 0itermax = 250etatable = 1.0/(distmat+np.diag([1e10]*numcity)) #启发函数矩阵,表示蚂蚁从城市i转移到矩阵j的期望程度pheromonetable = np.ones((numcity,numcity)) # 信息素矩阵pathtable = np.zeros((numant,numcity)).astype(int) #路径记录表distmat = getdistmat(coordinates) #城市的距离矩阵lengthaver = np.zeros(itermax) #各代路径的平均长度lengthbest = np.zeros(itermax) #各代及其之前遇到的最佳路径长度pathbest = np.zeros((itermax,numcity)) # 各代及其之前遇到的最佳路径长度while iter < itermax:# 随机产生各个蚂蚁的起点城市if numant <= numcity:#城市数比蚂蚁数多pathtable[:,0] = np.random.permutation(range(0,numcity))[:numant]else: #蚂蚁数比城市数多,需要补足pathtable[:numcity,0] = np.random.permutation(range(0,numcity))[:]pathtable[numcity:,0] = np.random.permutation(range(0,numcity))[:numant-numcity]length = np.zeros(numant) #计算各个蚂蚁的路径距离for i in range(numant):visiting = pathtable[i,0] # 当前所在的城市#visited = set() #已访问过的城市,防止重复#visited.add(visiting) #增加元素unvisited = set(range(numcity))#未访问的城市unvisited.remove(visiting) #删除元素for j in range(1,numcity):#循环numcity-1次,访问剩余的numcity-1个城市#每次用轮盘法选择下一个要访问的城市listunvisited = list(unvisited)probtrans = np.zeros(len(listunvisited))for k in range(len(listunvisited)):probtrans[k] = np.power(pheromonetable[visiting][listunvisited[k]],alpha)*np.power(etatable[visiting][listunvisited[k]],alpha)cumsumprobtrans = (probtrans/sum(probtrans)).cumsum()cumsumprobtrans -= np.random.rand()k = listunvisited[find(cumsumprobtrans>0)[0]] #下一个要访问的城市pathtable[i,j] = kunvisited.remove(k)#visited.add(k)length[i] += distmat[visiting][k]visiting = klength[i] += distmat[visiting][pathtable[i,0]] #蚂蚁的路径距离包括最后一个城市和第一个城市的距离#print length# 包含所有蚂蚁的一个迭代结束后,统计本次迭代的若干统计参数lengthaver[iter] = length.mean()if iter == 0:lengthbest[iter] = length.min()pathbest[iter] = pathtable[length.argmin()].()else:if length.min() > lengthbest[iter-1]:lengthbest[iter] = lengthbest[iter-1]pathbest[iter] = pathbest[iter-1].()else:lengthbest[iter] = length.min()pathbest[iter] = pathtable[length.argmin()].()# 更新信息素changepheromonetable = np.zeros((numcity,numcity))for i in range(numant):for j in range(numcity-1):changepheromonetable[pathtable[i,j]][pathtable[i,j+1]] += Q/distmat[pathtable[i,j]][pathtable[i,j+1]]changepheromonetable[pathtable[i,j+1]][pathtable[i,0]] += Q/distmat[pathtable[i,j+1]][pathtable[i,0]]pheromonetable = (1-rho)*pheromonetable + changepheromonetableiter += 1 #迭代次数指示器+1#观察程序执行进度,该功能是非必须的if (iter-1)%20==0:print iter-1# 做出平均路径长度和最优路径长度fig,axes = plt.subplots(nrows=2,ncols=1,figsize=(12,10))axes[0].plot(lengthaver,'k',marker = u'')axes[0].set_title('Average Length')axes[0].set_xlabel(u'iteration')axes[1].plot(lengthbest,'k',marker = u'')axes[1].set_title('Best Length')axes[1].set_xlabel(u'iteration')fig.savefig('Average_Best.png',dpi=500,bbox_inches='tight')plt.close()#作出找到的最优路径图bestpath = pathbest[-1]plt.plot(coordinates[:,0],coordinates[:,1],'r.',marker=u'$cdot$')plt.xlim([-100,2000])plt.ylim([-100,1500])for i in range(numcity-1):#m,n = bestpath[i],bestpath[i+1]print m,nplt.plot([coordinates[m][0],coordinates[n][0]],[coordinates[m][1],coordinates[n][1]],'k')plt.plot([coordinates[bestpath[0]][0],coordinates[n][0]],[coordinates[bestpath[0]][1],coordinates[n][1]],'b')ax=plt.gca()ax.set_title("Best Path")ax.set_xlabel('X axis')ax.set_ylabel('Y_axis')plt.savefig('Best Path.png',dpi=500,bbox_inches='tight')plt.close()
阅读全文

与pythonaxannotate相关的资料

热点内容
客户端框架源码 浏览:206
python自动办公能干嘛 浏览:873
程序员追爱 浏览:252
程序员逻辑故事 浏览:768
加密icsot23i2c 浏览:713
你们有什么好的解压软件 浏览:607
常州空气压缩机厂家 浏览:241
安卓如何关闭app内弹出的更新提示 浏览:409
e4a写的app怎么装苹果手机 浏览:201
海立压缩机海信系 浏览:210
社保如何在app上合并 浏览:220
小米加密照片后缀 浏览:236
我的世界网易手机怎么创服务器 浏览:978
载入单页源码 浏览:930
阿里云服务器seo 浏览:777
海洋斗什么时候上线安卓 浏览:86
中行app如何查每日汇款限额 浏览:840
输入服务器sn是什么意思 浏览:725
sha1算法java 浏览:90
asp代码压缩 浏览:851