如何在matplotlib图的特定区域上绘制矩形 [英] How to draw a rectangle over a specific region in a matplotlib graph

查看:347
本文介绍了如何在matplotlib图的特定区域上绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matplotlib中绘制了一个根据某些数据计算得出的图形.我想在此图的全局最大值周围绘制一个矩形区域.我尝试了plt.axhspan,,但是在调用plt.show()

I have a graph, computed from some data, drawn in matplotlib. I want to draw a rectangular region around the global maximum of this graph. I tried plt.axhspan, but the rectangle doesn't seem to appear when I call plt.show()

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

So, how can a rectangular region be drawn onto a matplotlib graph? Thanks!

推荐答案

最可能的原因是您在调用axhspan时使用了数据单元作为x参数.从该函数的文档(我的重点):

The most likely reason is that you used data units for the x arguments when calling axhspan. From the function's docs (my emphasis):

y坐标以数据单位为单位, x坐标以轴为单位(相对0-1) 单位.

y coords are in data units and x coords are in axes (relative 0-1) units.

因此,将任何向左延伸0或向右延伸1的矩形都简单地画在绘图外.

So any rectangle stretching left of 0 or right of 1 is simply drawn off-plot.

一种简单的替代方法可能是在轴上添加 Rectangle (例如,通过 plt.gca

An easy alternative might be to add a Rectangle to your axis (e.g., via plt.gca and add_patch); Rectangle uses data units for both dimensions. The following would add a grey rectangle with width & height of 1 centered on (2,3):

from matplotlib.patches import Rectangle
someX, someY = 2, 3
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 1, 1, facecolor="grey"))

这篇关于如何在matplotlib图的特定区域上绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆