2017-10-28 50 views
0

我已经在网站中搜索,但没有找到任何具体的我的情况。 我写了一段代码,绘制了一些点对,并为每对点写了一个标识符号。 问题是,识别号码太接近点,我想移动一些数字,使绘图更具可读性。 这是代码:重叠在matplotlib.pyplot.annotate

import os 
import numpy as np 
from math import exp, log10 
import matplotlib.pyplot as plt 

#dataset 
dataset1=np.genfromtxt(fname='/path/to/file1.txt') 
dataset2=np.genfromtxt(fname='/path/to/file2.txt')  
source=np.genfromtxt(fname='/path/to/file3.txt') 
num=np.array(source[:,0]) 

x1=np.array(dataset1[:,5]) 
y1=np.array(dataset1[:,20]) 
x2=np.array(dataset2[:,1]) 
y2=np.array(dataset2[:,10]) 

# error bars 
xe1=np.array(dataset1[:,6]) 
ye1=np.array(dataset1[:,21])  
xe2l=np.array(dataset2[:,2]) 
xe2u=np.array(dataset2[:,3]) 
ye2l=np.array(dataset2[:,11]) 
ye2u=np.array(dataset2[:,12]) 


plt.errorbar(x1, y1, xerr=xe1, yerr=ye1, fmt='.', color='red', elinewidth=1, capsize=2, label='wavdetect') 
plt.errorbar(x2, y2, xerr=[xe2l, xe2u], yerr=[ye2l, ye2u], fmt='.', color='blue', elinewidth=1, capsize=2, label='my_results') 

for i,j in enumerate(num): 
    plt.annotate(j, xy=(x2[i],y2[i]), ha='left', va='bottom') 

plt.xlabel('x') 
plt.ylabel('y') 
plt.title ('title') 
plt.legend(loc='upper right') 

plt.show() 

和剧情: enter image description here

回答

1

你为什么不只是添加一些白色的空间,您的注释?要做到这一点,你需要实际给annotate一个格式化的字符串,而不仅仅是数字。然后你可以玩弄你想要填充的空格和换行符的数量。

没有你的数据我不得不做出一些。希望它足够接近。

import numpy as np 
import matplotlib.pyplot as plt 

# Made up data 
x = np.array([ 312, 485, 100, 600, 200]) 
y = np.array([ .6, .2, .1, 1.2, 1.3 ]) 
xerr = x.max()/20 
yerr = y.max()/10 

plt.errorbar(x,y,xerr=xerr,yerr=yerr,fmt='.', color='red', elinewidth=1, capsize=2) 

for i,j in enumerate(num): 
    # Create a formatted string with three spaces, one newline 
    ann = ' {}\n'.format(j) 
    plt.annotate(ann, xy=(x[i],y[i])) 

enter image description here

请注意,如果你正在运行python2,你需要格式化字符串如ann = ' %.1f\n'%(j)

+0

非常感谢!现在它完美的作品! –