Matplotlib:如何指定 x 轴标签边界框的宽度

3

我正在尝试在MatPlotLib中创建一个堆叠条形图,其中顶部和底部有两个不同的x标签。上面的标签应该有一个边界框,宽度与条形本身相同。

不太正确的绘图

这是我创建标签的方法:

plt.tick_params(axis="both", left=False, bottom=False, labelleft=False)
plt.xticks(ind, diagram.keys())
ax.set_frame_on(False)

for label, x in zip([q[1] for q in diagram.values()], ind):
    ax.text(
        x, 1.05, '{:4.0%}'.format(label), 
        ha="center", va="center", 
        bbox={"facecolor": "blue", "pad": 3}
    )

diagram是一个类似于{底部标签: [[内容], 顶部标签]}的字典。

所以我想问的问题就是:如何操作文本对象的边界框?

非常感谢!

根据请求,这里有一个可运行的示例:

import matplotlib.pyplot as plt
import numpy as np


def stacked_bar_chart(
        diagram, title="example question", img_name="test_image", width=0.7, clusters=None, show_axes=True,
        show_legend=True, show_score=True):
    """
    Builds one or multiple scaled stacked bar charts for grade
    distributions. saves image as png.
    :param show_score: whether the score should be shown on top
    :param show_legend: whether the legend should be shown
    :param show_axes: whether question name should be shown on bottom
    :param clusters: indices of clusters to be displayed.
    :param width: the width of the bars as fraction of available space
    :param title: diagram title
    :param img_name: output path
    :param diagram: dictionary: {x-label: [[grade distribution], score]}
    :return: nothing.
    """

    grades = {
        "sehr gut":     "#357100",
        "gut":          "#7fb96a",
        "befriedigend": "#fdd902",
        "ausreichend":  "#f18d04",
        "mangelhaft":   "#e3540e",
        "ungenügend":   "#882d23"
    }

    # select clusters
    if clusters is not None:
        diagram = {i: diagram[i] for i in clusters}

    # normalize score distribution => sum of votes = 1.0
    normalized = []
    for question in diagram.values():
        s = sum(question[0])
        normalized.append([x / s for x in question[0]])

    # transpose dict values (score distributions) to list of lists
    transformed = list(map(list, zip(*normalized)))

    # input values for diagram generation
    n = len(diagram)  # number of columns
    ind = np.arange(n)  # x values for bar center
    base = [0] * n  # lower bounds for individual color set
    bars = []
    fig, ax = plt.subplots()

    # loop over grades
    for name, grade in zip(grades.keys(), transformed):
        assert len(grade) == n, \
            "something went wrong in plotting grade stack " + img_name
        bar = plt.bar(ind, grade, width=width, color=grades[name], bottom=base)
        bars.append(bar)

        # loop over bars
        for i, (rect, score) in enumerate(zip(bar, grade)):
            # update lower bound for next bar section
            base[i] += grade[i]
            # label with percentage
            # TODO text color white
            ax.text(
                rect.get_x() + width / 2, rect.get_height() / 2 + rect.get_y(), "{0:.0f}%".format(score * 100),
                va="center", ha="center")

    # label diagram

    plt.suptitle(title)
    if show_axes:
        plt.tick_params(axis="both", left=False, bottom=False, labelleft=False)
        plt.xticks(ind, diagram.keys())
        ax.set_frame_on(False)

    else:
        plt.tick_params(axis="both", left=False, bottom=False, labelleft=False, labelbottom=False)
        plt.axis("off")

    # show score label above
    if show_score:
        for label, x in zip([q[1] for q in diagram.values()], ind):
            ax.text(
                x, 1.05, '{:4.0%}'.format(label),
                ha="center", va="center",
                bbox={"facecolor": "blue", "pad": 3}
            )

    # create legend
    if show_legend:
        plt.legend(
            reversed(bars), reversed([*grades]),
            bbox_to_anchor=(1, 1), borderaxespad=0)

    # save file
    plt.show()


diagram = {
    "q1": [[1, 2, 3, 4, 5, 6], 0.6],
    "q2": [[2, 3, 1, 2, 3, 1], 0.4]
}
stacked_bar_chart(diagram)

1
这有点繁琐,参见这个问题,它想要为标题框做到这一点。当然,可以将其适应于条形图的宽度。另一方面,您可能更愿意在轴上放置一些文本,并在其背景中绘制所需尺寸的矩形。您希望采取哪种方向? - ImportanceOfBeingErnest
我更喜欢前一种变体。我已经尝试过绘制矩形的选项,但失败了,原因我记不清了...再说一遍,我是在寻求建议的人,所以我对你认为最好的任何建议都持开放态度。 - azrael
我可以尝试解决问题,但您能否提供一个 [mcve](请勿使用真实数据,只需提供可复制、粘贴和运行的示例)? - ImportanceOfBeingErnest
我尝试了,但还是有点太多了。有趣的部分在注释# show score label above附近。 - azrael
那不是最小可重现例 [mcve]。我自己创建了一个来回答这个问题。请注意,你不能期望别人为你完成这项工作。 - ImportanceOfBeingErnest
1个回答

5
为什么将文本框的宽度设置为定义好的宽度很困难,请参见此问题,该问题涉及设置标题文本框的宽度。原则上,那里的答案也可以在这里使用 - 这使得情况变得相当复杂。
相对较简单的解决方案是在数据坐标中指定文本的x位置,以及在轴坐标中指定其y位置。这允许创建一个与文本具有相同坐标的矩形,作为文本的边界框背景。
import matplotlib.pyplot as plt
import numpy as np

ind = [1,2,4,5]
data = [4,5,6,4]
perc = np.array(data)/float(np.array(data).sum())
width=0.7 
pad = 3 # points


fig, ax = plt.subplots()
bar = ax.bar(ind, data, width=width)

fig.canvas.draw()
for label, x in zip(perc, ind):
    text = ax.text(
        x, 1.00, '{:4.0%}'.format(label),
        ha="center", va="center" , transform=ax.get_xaxis_transform(), zorder=4)
    bb= ax.get_window_extent()
    h = bb.height/fig.dpi
    height = ((text.get_size()+2*pad)/72.)/h
    rect = plt.Rectangle((x-width/2.,1.00-height/2.), width=width, height=height,
                         transform=ax.get_xaxis_transform(), zorder=3,
                         fill=True, facecolor="lightblue", clip_on=False)
    ax.add_patch(rect)


plt.show()

enter image description here


非常感谢!就是这样。尽管由于我同时切换到使用Pandas创建实际条形图,可能出于某种原因,我不得不使用ax = plt.gca()fig = plt.gcf()而不是plt.subplots(),否则它会创建两个单独的图表。 - azrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接