我已经在网站上搜索过了,但没有发现任何具体的情况。我编写了一段代码,绘制了几对点,并为每对点编写了标识号。问题是,识别码离点太近了,我想稍微移动一下数字,以使情节更加可读性。这是代码:
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()以及情节:

发布于 2017-10-28 16:46:30
为什么不直接在注释中添加一些空白呢?要做到这一点,您需要实际给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]))

请注意,如果您正在运行python2,则需要将字符串格式化为ann = ' %.1f\n'%(j)。
https://stackoverflow.com/questions/46987930
复制相似问题