【问题标题】:Matplotlib artists to stay the same size when zoomed in?Matplotlib 艺术家在放大时保持相同的大小?
【发布时间】:2011-04-15 15:24:13
【问题描述】:

我正在使用 matplotlib 在图表上绘制一些艺术家(特别是几个矩形)。我想以某种方式锚定这些,以便无论使用什么缩放级别,它们都保持相同的大小。我用谷歌搜索,我已经阅读了大部分艺术家文档,但没有找到我需要锚定矩形大小的函数。

我希望得到详细说明如何执行此功能的答案,但如果您可以让我大致了解如何执行此操作,或者甚至给我一些关键字以使我的 Google 搜索更有效,我将不胜感激:)

谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    只需将transform=ax.transAxes 关键字应用于PolygonRectangle 实例。如果将补丁锚定到图形而不是轴更有意义,您也可以使用transFigureHere is the tutorial on transforms.

    下面是一些示例代码:

    from matplotlib import pyplot as plt
    from matplotlib.patches import Polygon
    import numpy as np
    x = np.linspace(0,5,100)
    y = np.sin(x)
    
    plt.plot(x,y)
    ax = plt.gca()
    
    polygon = Polygon([[.1,.1],[.3,.2],[.2,.3]], True, transform=ax.transAxes)
    ax.add_patch(polygon)
    
    plt.show()
    

    如果您不想使用轴坐标系放置多边形,而是希望使用数据坐标系对其进行定位,那么您可以使用变换在定位前静态转换数据。最好的例子在这里:

    from matplotlib import pyplot as plt
    from matplotlib.patches import Polygon
    import numpy as np
    
    x = np.linspace(0,5,100)
    y = np.sin(x)
    
    plt.plot(x,y)
    ax = plt.gca()
    
    dta_pts = [[.5,-.75],[1.5,-.6],[1,-.4]]
    
    # coordinates converters:
    #ax_to_display = ax.transAxes.transform
    display_to_ax = ax.transAxes.inverted().transform
    data_to_display = ax.transData.transform
    #display_to_data = ax.transData.inverted().transform
    
    ax_pts = display_to_ax(data_to_display(dta_pts))
    
    # this triangle will move with the plot
    ax.add_patch(Polygon(dta_pts, True)) 
    # this triangle will stay put relative to the axes bounds
    ax.add_patch(Polygon(ax_pts, True, transform=ax.transAxes))
    
    plt.show()
    

    【讨论】:

    • 有没有一种方法可以修改它,这样一个多边形就可以 1) 始终包含相同的数据标记(围绕它们的矩形),因此必须随着平移而移动,但 2) 不会增长放大时变大?我想要一个比标记高一点但不应该随着放大或缩小而增长或缩小的“突出显示栏”。
    • @Chelonian 1)据我了解,您的标准似乎不是自洽的。当缩放足够远时,多个点必然会留下一个恒定大小的框,对吗? 2)作为这个答案的简单模式,没有什么能立即让我跳出来。我建议发布一个与此相关的新问题。
    • 我不明白你的第二句话,但我会按照你的建议发布一个新问题。谢谢。
    • 我在这里添加了新问题:stackoverflow.com/questions/9812450/…
    猜你喜欢
    • 1970-01-01
    • 2014-08-19
    • 2017-02-19
    • 2016-06-17
    • 2012-07-10
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    相关资源
    最近更新 更多