【问题标题】:Subclassing matplotlib Text: manipulate properties of child artist子类化 matplotlib 文本:操作子艺术家的属性
【发布时间】:2016-03-01 20:29:27
【问题描述】:

我正在实现一个用于线对象内联标签的类。为此,我创建了Text 类的子类,它作为Line2D 对象作为属性。我的previous post 中的代码可能有点长,所以我在这里隔离了问题:

from matplotlib.text import Text
from matplotlib import pyplot as plt
import numpy as np


class LineText(Text):
    def __init__(self,line,*args,**kwargs):
        x_pos = line.get_xdata().mean()
        y_pos = line.get_ydata().mean()
        Text.__init__(self,x=x_pos,y=y_pos,*args,**kwargs)
        self.line = line
    def draw(self,renderer):
        self.line.set_color(self.get_color())
        self.line.draw(renderer = renderer)
        Text.draw(self,renderer)



if __name__ == '__main__':

    x = np.linspace(0,1,20)
    y = np.linspace(0,1,20)
    ax = plt.subplot(1,1,1)
    line = plt.plot(x,y,color = 'r')[0]
    linetext = LineText(line,text = 'abc')
    ax.add_artist(linetext)
    plt.show()

该类采用从plot 函数返回的Line2D 句柄,并在.draw 方法中对该行进行了一些更改。出于说明目的,我在这里只是尝试改变它的颜色。

改变线条颜色后,我调用线条draw。然而,这并没有达到预期的效果。当第一次绘制图形时,似乎有一条红线和一条黑线叠加在一起。一旦图形被调整大小或以其他方式强制重绘,线条就会按预期改变其颜色。到目前为止,我发现在打开时强制正确绘制图形的唯一方法是在show() 之前添加plt.draw()。然而,这确实让人感到笨拙。

我能以某种方式强制只重绘线对象吗?还是我做错了?

提前致谢。

【问题讨论】:

    标签: python python-2.7 matplotlib


    【解决方案1】:

    问题是你没有更新行直到它被重绘,我认为这应该可行:

    class LineText(Text):
        def __init__(self,line,*args,**kwargs):
        x_pos = line.get_xdata().mean()
        y_pos = line.get_ydata().mean()
        Text.__init__(self,x=x_pos,y=y_pos,*args,**kwargs)
        self.line = line
        self.line.set_color(self.get_color())
        plt.gca().add_artist(self.line)   # You could also pass `ax` instead of calling `plt.gca()`
        plt.gca().add_artist(self)
    
    
    if __name__ == '__main__':
    
        x = np.linspace(0,1,20)
        y = np.linspace(0,1,20)
        ax = plt.subplot(1,1,1)
        line = plt.plot(x,y, 'r--', alpha=0.5)[0]
        linetext = LineText(line,text = 'abc')
        # ax.add_artist(linetext)     # Artist is being added in `__init__` instead                                                                                                                                                                         
        plt.show(block=False)
    

    【讨论】:

    • 感谢您的回答。不过,这并不是我想要的。我从plt.plot 获得线对象的句柄,所以它已经被添加到轴上。另外,我不想将文本本身添加到它自己的轴中 __init__ 因为这似乎不是艺术家在 matplotlib 中的行为方式......
    猜你喜欢
    • 2017-02-19
    • 2019-11-24
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多