【问题标题】:Python/Matplotlib - How to put text in the corner of equal aspect figurePython/Matplotlib - 如何将文本放在等宽图形的角落
【发布时间】:2013-04-20 16:04:11
【问题描述】:

我想把文字放在等宽图形的右下角。 我通过 ax.transAxes 设置相对于图形的位置, 但我必须根据每个图形的高度比例手动定义相对坐标值。

了解坐标轴高度比例和脚本中正确文本位置的好方法是什么?

 ax = plt.subplot(2,1,1)
 ax.plot([1,2,3],[1,2,3])
 ax.set_aspect('equal')
 ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
 print ax.get_position().height

 ax = plt.subplot(2,1,2)
 ax.plot([10,20,30],[1,2,3])
 ax.set_aspect('equal')
 ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
 print ax.get_position().height                                              

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    使用annotate

    事实上,我几乎从不使用text。即使我想在数据坐标中放置东西,我通常也希望将其偏移一些固定的点距离,这使用annotate 更容易。

    举个简单的例子:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
    
    axes[0].plot(range(1, 4))
    axes[1].plot(range(10, 40, 10), range(1, 4))
    
    for ax in axes:
        ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                    horizontalalignment='right', verticalalignment='bottom')
    plt.show()
    

    如果您希望它稍微偏离角落,您可以通过xytext kwarg 指定一个偏移量(和textcoords 来控制xytext 的值的解释方式)。我在这里也使用了hava 的缩写horizontalalignmentverticalalignment

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
    
    axes[0].plot(range(1, 4))
    axes[1].plot(range(10, 40, 10), range(1, 4))
    
    for ax in axes:
        ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                    xytext=(-5, 5), textcoords='offset points',
                    ha='right', va='bottom')
    plt.show()
    

    如果您尝试将其放置在轴下方,您可以使用偏移量将其放置在点下方的设定距离:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
    
    axes[0].plot(range(1, 4))
    axes[1].plot(range(10, 40, 10), range(1, 4))
    
    for ax in axes:
        ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                    xytext=(0, -15), textcoords='offset points',
                    ha='right', va='top')
    plt.show()
    

    还可以查看Matplotlib annotation guide 了解更多信息。

    【讨论】:

    • 这是一个很好的答案和例子。我将尝试使用注释而不是文本。非常感谢。
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2015-06-02
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多