【问题标题】:How to draw a rectangle over a specific region in a matplotlib graph如何在 matplotlib 图中的特定区域上绘制矩形
【发布时间】:2012-10-22 14:39:00
【问题描述】:

我有一个图表,根据一些数据计算,在 matplotlib 中绘制。我想在该图的全局最大值周围绘制一个矩形区域。我试过plt.axhspan,,但是当我调用plt.show()时矩形似乎没有出现

那么,如何将矩形区域绘制到 matplotlib 图上?谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这是一个示例,演示如何在散点图上绘制矩形边界框:

    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import numpy as np
    
    data = np.array([
        [.9, .9], [.85, 2.1], [1.2, 1.], [2.1, .95], [3., 1.1],
        [3.9, .7], [4., 1.4], [4.2, 1.8], [2., 2.3], [3., 2.3],
        [1.5, 1.8], [2., 1.5], [2.2, 2.], [2.6, 1.7], [2.7, 1.85]
    ])
    categories = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
    color1 = (0.69, 0.34, 0.15, 1.0)
    color2 = (0.65, 0.80, 0.89, 1.0)
    colormap = np.array([color1, color2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(
        x=[data[:, 0]],
        y=[data[:, 1]],
        c=colormap[categories],
        marker='o', alpha=0.9)
    
    margin = .1
    min_f0, max_f0 = min(data[10:, 0]) - margin, max(data[10:, 0]) + margin
    min_f1, max_f1 = min(data[10:, 1]) - margin, max(data[10:, 1]) + margin
    width = max_f0 - min_f0
    height = max_f1 - min_f1
    
    ax.add_patch(
        patches.Rectangle(
            xy=(min_f0, min_f1),  # point of origin.
            width=width, height=height, linewidth=1,
            color='red', fill=False))
    plt.show()
    

    输出:

    【讨论】:

      【解决方案2】:

      最可能的原因是您在调用 axhspan 时为 x 参数使用了数据单位。来自the function's docs(我的重点):

      y 坐标在数据单元中,x 坐标在轴中(相对于 0-1) 单位

      因此,任何从 0 向左或从 1 向右延伸的矩形都只是在绘图之外绘制。

      一个简单的替代方法可能是将Rectangle 添加到您的轴(例如,通过plt.gcaadd_patch); Rectangle 对两个维度都使用数据单元。以下将添加一个以 (2,3) 为中心的宽度和高度为 1 的灰色矩形:

      from matplotlib.patches import Rectangle
      import matplotlib.pyplot as plt
      
      fig = plt.figure()
      plt.xlim(0, 10)
      plt.ylim(0, 12)
      
      someX, someY = 2, 5
      currentAxis = plt.gca()
      currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor="grey"))
      

      • 没有facecolor
      currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 4, 6, facecolor="none", ec='k', lw=2))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-22
        • 2012-11-03
        • 1970-01-01
        • 2023-01-30
        • 2012-08-16
        • 1970-01-01
        • 2022-08-06
        • 1970-01-01
        相关资源
        最近更新 更多