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

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

问题描述

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

时矩形似乎没有出现

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

解决方案

最可能的原因是您在调用 axhspan 时为 x 参数使用了数据单元.来自

  • 没有facecolor

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

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()

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

解决方案

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 coords are in data units and x coords are in axes (relative 0-1) units.

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

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
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"))

  • Without facecolor

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

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

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