繁体   English   中英

如何在 matplotlib 图表中找到矩形的“真实”区域?

[英]How do I find the 'real' area of a rectangle in a matplotlib chart?

我在一个图中有两个条形图子图。 我想知道两个子图之间条形的总面积如何比较。 我知道ax.bar()返回一个 Rectangle 对象的集合,我尝试通过以下方式计算它们的面积:

from matplotlib import pyplot as plt
fig, (ax1, ax2) = plt.subplots(1,2)

def get_area(rects):
    area = 0
    for rect in rects:
        area += rect.get_width() * rect.get_height()
    return area

x = range(3)
y1 = [2, 3, 4]
y2 = [20, 30, 30]
r = ax1.bar(x, y1)
print "Total area of bars in first subplot = {:.1f}".format(get_area(r))
r = ax2.bar(x, y2)
print "Total area of bars in 2nd subplot = {:.1f}".format(get_area(r))

这打印:

Total area of bars in first subplot = 7.2
Total area of bars in 2nd subplot = 64.0

看看实际数字,这显然不是我想要捕捉的现实。

两个不同比例的条形图子图

似乎这给了我“数据单元”中的区域,但我真正关心的是他们在屏幕上使用了多少空间。

诀窍是使用ax.transData从数据坐标转换为显示坐标。 我发现这个关于转换的教程有助于解决这个问题。

from matplotlib import pyplot as plt
import numpy as np

def get_area(ax, rects):
    area = 0
    for rect in rects:
        bbox = rect.get_bbox()
        bbox_display = ax.transData.transform_bbox(bbox)
        # For some reason, bars going right-to-left will have -ve width.
        rect_area = abs(np.product(bbox_display.size))
        area += rect_area
    return area

fig, (ax1, ax2) = plt.subplots(1,2)

x = range(3)
y1 = [2, 3, 4]
y2 = [20, 30, 30]
r = ax1.bar(x, y1)
print "Real area of bars in first subplot = {:.1f}".format(get_area(ax1, r))
r = ax2.bar(x, y2)
print "Real area of bars in 2nd subplot = {:.1f}".format(get_area(ax2, r))

新输出:

Real area of bars in first subplot = 18417.7
Real area of bars in 2nd subplot = 21828.4

(要注意的小问题: bbox.size有时可以给出负的宽度或高度。在这个重现示例中这不是问题,但我在水平条形图上观察到它,条形图从右到左。更好地取绝对值是安全的。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM