我正在尝试在下面的代码中将手动标签添加到等值线图中。标签随机打印。有谁知道如何解决这个问题?这似乎是Matplotlib中的一个错误。
此致 大卫
import numpy as np
import matplotlib.pyplot as plt
a = 0.2
resolution = 100
xarray = np.linspace(0,0.25,num=resolution)
yarray = np.linspace(0,1,num=resolution)
A = np.empty([resolution,resolution])
xc = 0
yc = 0
for x in xarray:
for y in yarray:
#print xc,yc
wp = 1./np.pi*np.arctan(np.sin(np.pi*y)*np.sinh(np.pi*a/2.)/
(np.cosh(np.pi*x)-np.cos(np.pi*y)*np.cosh(np.pi*a/2.)))
if wp <= 0:
wp = wp+1
A[xc, yc] = wp
else:
A[xc, yc] = wp
yc += 1
yc=0
xc += 1
A = A.transpose()
B = np.fliplr(A)
AB = np.hstack((B,A))
fullx = np.hstack((-xarray[::-1],xarray))
#plot
fig = plt.figure()
fig.suptitle("Weighting potential")
ax = plt.subplot(1,1,1)
CS = plt.contour(fullx,yarray,AB,10, colors='k')
labelpos = np.dstack((np.zeros(9),np.arange(0.1,1,0.1)))[0]
plt.clabel(CS,inline=True, fmt='%1.1f',fontsize=9, manual=labelpos)
plt.show()
答案 0 :(得分:2)
这是预期的行为。
它为x, y
参数中包含的每个manual
数据坐标选择最接近的轮廓曲线。当找到许多坐标的相同轮廓曲线时,可能会发生它们会开始凝聚,就像你的情况一样。
如果您使用:
y_pick = [0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.5]
labelpos = ((0, i) for i in y_pick)
你会得到类似的东西:
超出主题:
您可以对代码进行矢量化,避免相对较慢的for
循环:
import numpy as np
import matplotlib.pyplot as plt
a = 0.2
def fwp(x, y, a):
return (1./np.pi*np.arctan(np.sin(np.pi*y)*np.sinh(np.pi*a/2.)/
(np.cosh(np.pi*x)-np.cos(np.pi*y)*np.cosh(np.pi*a/2.))))
resolution = 100
xarray = np.linspace(0, 0.25, num=resolution)
yarray = np.linspace(0, 1, num=resolution)
x, y = np.meshgrid(xarray, yarray, copy=False)
A = fwp(x, y, a)
A[A<=0] += 1
B = np.fliplr(A)
AB = np.hstack((B, A))