matplotlib 有可能有一个以上的字幕吗?

bweufnob  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(147)

如果我有一个带有子图的matplotlib图,是否可以有多个suptitle?(有点像常规标题的loc ='center',loc ='left'和loc ='right'参数)。
在下面的示例中,suptitle的多个示例被覆盖,图中只显示最后一个suptitle。

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

plt.suptitle('center title')
plt.suptitle('right title', x=.8)
plt.suptitle('left title', x=.2)

wnrlj8wa

wnrlj8wa1#

我想到的最好的解决方案是在图中添加文本,并根据图形的坐标用参数transform=fig.transFigure调整位置。

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

plt.text(.5, 1, 'center title', transform=fig.transFigure, horizontalalignment='center')
plt.text(.8, 1, 'right title', transform=fig.transFigure, horizontalalignment='center')
plt.text(.2, 1, 'left title', transform=fig.transFigure, horizontalalignment='center')

bwleehnv

bwleehnv2#

在@blaylockbk上构建

def fig_title(
    fig: matplotlib.figure.Figure, txt: str, loc="center", fontdict=None, **kwargs
):
    """Alternative to fig.suptitle that behaves like ax.set_title.
    DO NOT use with suptitle.

    See also:
    https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_title.html
    https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.suptitle.html
    https://stackoverflow.com/a/77063164/8954109
    """
    if fontdict is not None:
        kwargs = {**fontdict, **kwargs}
    if "fontsize" not in kwargs and "size" not in kwargs:
        kwargs["fontsize"] = plt.rcParams["axes.titlesize"]

    if "fontweight" not in kwargs and "weight" not in kwargs:
        kwargs["fontweight"] = plt.rcParams["figure.titleweight"]

    if "verticalalignment" not in kwargs:
        kwargs["verticalalignment"] = "top"
    if "horizontalalignment" not in kwargs:
        kwargs["horizontalalignment"] = "center"

    x = 0
    if loc == "left":
        x = 0.2
    elif loc == "center":
        x = 0.5
    elif loc == "right":
        x = 0.8
    else:
        raise ValueError(f"invalid loc: {loc}")

    # Tell the layout engine that our text is using space at the top of the figure
    # so that tight_layout does not break.
    # Is there a more direct way to do this?
    fig.suptitle(" ")
    text = fig.text(x, 0.98, txt, transform=fig.transFigure, in_layout=True, **kwargs)

    return text

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

ax1.set_title("ax1 title")
ax1.xaxis.tick_top()
ax1.xaxis.set_label_position("top")
ax1.set_xlabel("xlab")
ax1.set_ylabel("ylab")

ax2.set_xlabel("xlab")
ax2.set_ylabel("ylab")
ax2.set_title("ax2 title")

# fig.suptitle("suptitle") # Would be overwritten

fig_title(fig, "left", loc="left")
fig_title(fig, "center")
fig_title(fig, "right", loc="right")

# fig.suptitle("suptitle") # Would overlap

fig.tight_layout()

# fig.savefig("test.png")

相关问题