首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Matplotlib中的内联标签

Matplotlib中的内联标签
EN

Stack Overflow用户
提问于 2013-06-08 03:59:23
回答 2查看 142.8K关注 0票数 119

在Matplotlib中,创建一个图例(example_legend(),下图)并不太难,但我认为将标签放在正在绘制的曲线上(如example_inline()中,下图)会更好。这可能非常麻烦,因为我必须手动指定坐标,并且,如果我重新格式化绘图,我可能必须重新定位标签。有没有办法在Matplotlib中自动生成曲线上的标签?能够以与曲线角度相对应的角度调整文本方向的加分。

import numpy as np
import matplotlib.pyplot as plt

def example_legend():
    plt.clf()
    x = np.linspace(0, 1, 101)
    y1 = np.sin(x * np.pi / 2)
    y2 = np.cos(x * np.pi / 2)
    plt.plot(x, y1, label='sin')
    plt.plot(x, y2, label='cos')
    plt.legend()

def example_inline():
    plt.clf()
    x = np.linspace(0, 1, 101)
    y1 = np.sin(x * np.pi / 2)
    y2 = np.cos(x * np.pi / 2)
    plt.plot(x, y1, label='sin')
    plt.plot(x, y2, label='cos')
    plt.text(0.08, 0.2, 'sin')
    plt.text(0.9, 0.2, 'cos')

EN

回答 2

Stack Overflow用户

发布于 2021-12-02 13:41:10

matplotx (我编写的)有line_labels(),它将标签绘制在线条的右侧。当太多的行集中在一个点上时,它也足够聪明,可以避免重叠。(有关示例,请参阅stargraph。)它通过解决标签目标位置上的特定非负最小二乘问题来实现这一点。无论如何,在许多情况下,在一开始就没有重叠的情况下,比如下面的例子,甚至没有必要这样做。

import matplotlib.pyplot as plt
import matplotx
import numpy as np

# create data
rng = np.random.default_rng(0)
offsets = [1.0, 1.50, 1.60]
labels = ["no balancing", "CRV-27", "CRV-27*"]
x0 = np.linspace(0.0, 3.0, 100)
y = [offset * x0 / (x0 + 1) + 0.1 * rng.random(len(x0)) for offset in offsets]

# plot
with plt.style.context(matplotx.styles.dufte):
    for yy, label in zip(y, labels):
        plt.plot(x0, yy, label=label)
    plt.xlabel("distance [m]")
    matplotx.ylabel_top("voltage [V]")  # move ylabel to the top, rotate
    matplotx.line_labels()  # line labels to the right
    plt.show()
    # plt.savefig("out.png", bbox_inches="tight")

票数 2
EN

Stack Overflow用户

发布于 2020-07-18 00:43:17

像Ioannis Filippidis这样的更简单的方法:

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16992038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档