Set multiple titles for a matplotlib subplot

与世无争的帅哥 提交于 2020-01-05 06:39:12

问题


I'm creating subplots of venn diagrams that are made via matplotlib_venn. Here is the plot I'm making:

Notice the missing title on the top-right plot. This is because whenever I call ax.set_title, it's replacing existing subplot titles. The code to create this plot was:

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 is a function that calls matplotlib_venn.venn3_unweighted. df is a pandas.DataFrame of the data.

In the matplotlib title demo, it seems like you can set multiple titles... but I can't figure out how to do this with subplots.

There's an answer to a similar question that suggests using set_ylabel. However, setting the ylabel has no effect on these venn plots.


回答1:


The problem is that each axes subplots has exactly one title. If you call set_title a second time, the first title will be replaced.
There is not much of a difference between a title and a text. So you can decide to use titles for the columns and texts for the rows.

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()



来源:https://stackoverflow.com/questions/47777296/set-multiple-titles-for-a-matplotlib-subplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!