Python 为什么不';重叠的注释不会在图中重新排列吗?
我在堆栈溢出中找到了一些关于修复matplotlib中重叠注释的代码。我想测试一下,所以我把它复制到我自己的iPython笔记本上。然而,当我运行它时,它没有相同的输出 代码的要点是测试注释是否重叠,如果重叠,则移动它们,使其不重叠,并放置一个红色箭头以显示它们所描述的数据点。然而,当我自己运行代码时,这并没有发生 我正在使用Python 3 以下是原始链接: 代码如下所示:Python 为什么不';重叠的注释不会在图中重新排列吗?,python,matplotlib,Python,Matplotlib,我在堆栈溢出中找到了一些关于修复matplotlib中重叠注释的代码。我想测试一下,所以我把它复制到我自己的iPython笔记本上。然而,当我运行它时,它没有相同的输出 代码的要点是测试注释是否重叠,如果重叠,则移动它们,使其不重叠,并放置一个红色箭头以显示它们所描述的数据点。然而,当我自己运行代码时,这并没有发生 我正在使用Python 3 以下是原始链接: 代码如下所示: import sys import matplotlib import matplotlib.pyplot as plt
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def get_text_positions(text, x_data, y_data, txt_width, txt_height):
a = zip(y_data, x_data)
text_positions = list(y_data)
for index, (y, x) in enumerate(a):
local_text_positions = [i for i in a if i[0] > (y - txt_height)
and (abs(i[1] - x) < txt_width * 2) and i != (y,x)]
if local_text_positions:
sorted_ltp = sorted(local_text_positions)
if abs(sorted_ltp[0][0] - y) < txt_height: #True == collision
differ = np.diff(sorted_ltp, axis=0)
a[index] = (sorted_ltp[-1][0] + txt_height, a[index][1])
text_positions[index] = sorted_ltp[-1][0] + txt_height*1.01
for k, (j, m) in enumerate(differ):
#j is the vertical distance between words
if j > txt_height * 2: #if True then room to fit a word in
a[index] = (sorted_ltp[k][0] + txt_height, a[index][2])
text_positions[index] = sorted_ltp[k][0] + txt_height
break
return text_positions
def text_plotter(text, x_data, y_data, text_positions, txt_width,txt_height):
for z,x,y,t in zip(text, x_data, y_data, text_positions):
plt.annotate(str(z), xy=(x-txt_width/2, t), size=12)
if y != t:
plt.arrow(x, t,0,y-t, color='red',alpha=0.3, width=txt_width*0.1,
head_width=txt_width, head_length=txt_height*0.5,
zorder=0,length_includes_head=True)
# start new plot
plt.clf()
plt.xlabel("Proportional Euclidean Distance")
plt.ylabel("Percentage Timewindows Attended")
plt.title("Test plot")
together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
together.sort()
text = [x for (x,y,z) in together]
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]
p1 = plt.plot(eucs,covers,color="black", alpha=0.5)
txt_height = 0.0037*(plt.ylim()[1] - plt.ylim()[0])
txt_width = 0.018*(plt.xlim()[1] - plt.xlim()[0])
text_positions = get_text_positions(text, eucs, covers, txt_width, txt_height)
text_plotter(text, eucs, covers, text_positions, txt_width, txt_height)
plt.show()
导入系统
导入matplotlib
将matplotlib.pyplot作为plt导入
将numpy作为np导入
def get_text_位置(文本、x_数据、y_数据、txt_宽度、txt_高度):
a=zip(y_数据,x_数据)
文本位置=列表(y数据)
对于枚举(a)中的索引(y,x):
局部文本位置=[i为i,如果i[0]>(y-txt\u高度)
和(abs(i[1]-x)如何使其工作?更改注释文本的字体大小以适应位置手动更改注释文本的字体大小以适应位置手动