本文介绍了如何在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):

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

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

一种简单的替代方法可能是在轴上添加 Rectangle (例如,通过 plt.gca 和); Rectangle使用两个维度的数据单位.以下将添加一个灰色矩形,其宽度为& 1的高度以(2,3)为中心:

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图的特定区域上绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 02:03