高度变量"barh" matplotlib 的单位是什么?



在matplotlib的函数barh的定义中:

matplotlib.pyplot.barh(bottom, width, height=0.8, left=None, hold=None, **kwargs)

默认的"高度"是0.8,但当我绘制一些具有不同图形高度的图形时,例如(30,40,..(和dpi=100。我看到酒吧的高度变了。它不是固定的。所以我想知道barh中的高度单位是什么,以及如何使其固定(不取决于图形的高度(。

我将把它分成两部分:

我想知道barh 中的高度单位是多少

(显然,自2009年以来,人们一直在想这个问题……所以我想你是一个很好的伙伴!(

这个问题比较简单-它是分配给图中条形图的高度的百分比。例如,默认的height=0.8意味着条形图的高将是0.8 * (plot_height / n_bars)。您可以通过设置height=1.0来看到这一点(即使值>1,条形图也会重叠(。

如果你真的想确定,这里是axes.barh的来源。这只是调用axes.bar-看看这些行:

nbars = len(bottom)
if len(left) == 1:
    left *= nbars
if len(height) == 1:
    height *= nbars

稍后…

args = zip(left, bottom, width, height, color, edgecolor, linewidth)
for l, b, w, h, c, e, lw in args:
    if h < 0:
        b += h
        h = abs(h)
    if w < 0:
        l += w
        w = abs(w)
    r = mpatches.Rectangle(
        xy=(l, b), width=w, height=h,
        facecolor=c,
        edgecolor=e,
        linewidth=lw,
        label='_nolegend_',
        margins=margins
        )
    r.update(kwargs)
    r.get_path()._interpolation_steps = 100
    #print r.get_label(), label, 'label' in kwargs
    self.add_patch(r)
    patches.append(r)

因此,您可以看到高度按nbars缩放,当您绘制矩形时,它们按此高度隔开。

如何使其固定

这更难,你必须手动设置。图表上的条形图最终是matplotlib.patches.Rectangle对象,它们有宽度和高度。。。这也是一个百分比。我认为最好的解决方案是手动计算适当的百分比。

以下是一个基于barh演示的简短示例:

import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
plt.figure(figsize=(5,5), dpi=80)
myplot = plt.barh(y_pos, performance, height=0.8, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
for obj in myplot:
    # Let's say we want to set height of bars to always 5px..
    desired_h = 5
    current_h = obj.get_height()
    current_y = obj.get_y()
    pixel_h = obj.get_verts()[2][1] - obj.get_verts()[0][1]
    print("current position = ", current_y)
    print("current pixel height = ", pixel_h)
    # (A) Use ratio of pixels to height-units to calculate desired height
    h = desired_h / (pixel_h/current_h)
    obj.set_height(h)
    pixel_h = obj.get_verts()[2][1] - obj.get_verts()[0][1]
    print("now pixel height = ", pixel_h)
    # (B) Move the rectangle so it still aligns with labels and error bars
    y_diff = current_h - h # height is same units as y
    new_y = current_y + y_diff/2
    obj.set_y(new_y)
    print("now position = ", obj.get_y())
plt.show()

A部分计算pixel_h/current_h以获得像素和高度单位之间的转换。然后,我们可以将desired_h(像素(除以该比率,以获得以高度为单位的desired_h。这将条宽度设置为5像素,但条的底部保持在同一位置,因此不再与标签和错误条对齐。

部分B计算新的y位置。由于yheight在相同的单元中,我们只需将高度差的一半(y_diff(相加即可获得新的位置。这将使条形图保持在原始y位置的中心。

请注意,这仅设置初始大小。例如,如果调整绘图的大小,条形图仍将按比例缩放——您必须覆盖该事件才能适当调整条形图的大小。

最新更新