防止标签文本重叠Matplotlib Python中的线图

发布于 2025-02-11 14:12:40 字数 1039 浏览 1 评论 0 原文

我尝试绘制由X_TN,Y_TN列表协调为(x,y)的线,并以系列顺序标记为Seri列表。我的简化代码如下所示。但是,标签已与我的线路重叠,例如(1)和(6)。如何让我的标签一般躲避行?谢谢。

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

x_tn = [0,1,1,2,3,2,2]
y_tn = [0,0,1,2,1,1,0]
seri = [0,1,2,3,4,5,6]

plt.title("Function") 
plt.xlabel("x") 
plt.ylabel("y")

plt.plot(x_tn, y_tn, '-ok')

for x,y,k in zip(x_tn,y_tn,seri):

    label = f"({k})"

    plt.annotate(label, # this is the text
        (x,y), # these are the coordinates to position the label
        textcoords="offset points", # how to position the text
        xytext=(0,10), # distance from text to points (x,y)
        ha='center') # horizontal alignment can be left, right or center

#specify axis tick step sizes
plt.xticks(np.arange(min(x_tn), max(x_tn)+1, 1))
plt.yticks(np.arange(min(y_tn), max(y_tn)+1, 1))
    
plt.show()

I try to draw a line coordinated by the x_tn, y_tn list as (x,y) and labeled by a series order as the seri list. My simplified code is as follows below. However, labels have overlapped with my line in a few locations such as (1) and (6). How to let my labels dodge the line generally? Thank you.

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

x_tn = [0,1,1,2,3,2,2]
y_tn = [0,0,1,2,1,1,0]
seri = [0,1,2,3,4,5,6]

plt.title("Function") 
plt.xlabel("x") 
plt.ylabel("y")

plt.plot(x_tn, y_tn, '-ok')

for x,y,k in zip(x_tn,y_tn,seri):

    label = f"({k})"

    plt.annotate(label, # this is the text
        (x,y), # these are the coordinates to position the label
        textcoords="offset points", # how to position the text
        xytext=(0,10), # distance from text to points (x,y)
        ha='center') # horizontal alignment can be left, right or center

#specify axis tick step sizes
plt.xticks(np.arange(min(x_tn), max(x_tn)+1, 1))
plt.yticks(np.arange(min(y_tn), max(y_tn)+1, 1))
    
plt.show()

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笔绘流年 2025-02-18 14:12:40

xytext=(7,10), # distance from text to points (x,y)

通过此代码更改标签位置

enter image description here

xytext=(7,10), # distance from text to points (x,y)

Change label location by this piece of code

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文