为matplotlib subp设置多个标题

2024-09-27 21:34:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建通过^{}生成的维恩图的子图。下面是我的情节:

Subplots missing top-right title

请注意右上角绘图中缺少的标题。这是因为每当我调用ax.set_title时,它都会替换现有的子批次标题。创建此绘图的代码是:

oadoi_colors = ['all', 'closed', 'closed + green', 'bronze', 'green', 'hybrid', 'gold']
collections = ['Combined', 'Crossref', 'Unpaywall', 'Web of Science']
figure, axes = matplotlib.pyplot.subplots(nrows=len(oadoi_colors), ncols=len(collections), figsize=(2.7 * len(collections), 2.7 * len(oadoi_colors)))
subplot_label_rectprops = {'facecolor': '#fef2e2', 'boxstyle': 'round'}

for (oadoi_color, collection), df in coverage_df.groupby(['oadoi_color', 'collection']):
    i = oadoi_colors.index(oadoi_color)
    j = collections.index(collection)
    ax = axes[i, j]
    venn_plotter(df, ax=ax)
    if i == 0:
        text = ax.set_title(collection, loc='center', y=1.1)
        text.set_bbox(subplot_label_rectprops)
        # Top-right subplot cannot titled twice: https://stackoverflow.com/questions/36602347
    if j == len(collections) - 1:
        text = ax.set_title(oadoi_color.title(), x=1.1, y=0.5, verticalalignment='center', rotation=270)
        text.set_bbox(subplot_label_rectprops)

venn_plotter是一个调用matplotlib_venn.venn3_unweighted的函数。df是数据的pandas.DataFrame。在

在matplotlibtitle demo中,似乎可以设置多个标题。。。但我不知道如何用子批次来做这个。在

有一个answer to a similar question建议使用set_ylabel。但是,设置ylabel对这些venn图没有影响。在


Tags: text标题dflentitleaxcollectionslabel
1条回答
网友
1楼 · 发布于 2024-09-27 21:34:43

问题是每个轴的子图都只有一个标题。如果您再次调用set_title,则第一个标题将被替换。
标题和正文没有太大区别。因此,您可以决定对列使用标题,对行使用文本。在

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3,3)
for i in range(3):
    for j in range(3):
        ax = axes[i,j]
        if i == 0:
            title = ax.set_title("column title", loc='center', y=1.1)
        if j == 2:
            text = ax.text(1.1,0.5,"row title", size=12,
                           verticalalignment='center', rotation=270)

plt.show()

enter image description here

相关问题 更多 >

    热门问题