Matplotlib标题跨越两个(或任意数量)子批次列

2024-09-27 09:23:58 发布

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

由于我所绘制内容的性质,我希望子图类似于嵌套表。 我不知道如何清楚地问这个问题,所以我将添加一些图片来代替,我希望能说明这个问题。在

我所拥有的:

Matplotlib graphs with title and axes titles

我想要的:

Matplotlib graphs with title and axes titles AND wanted sub-titles

当前(缩短)代码如下所示:

fig, axes = plt.subplots(nrows=5, ncols=4) 
fig.suptitle(title, fontsize='x-large')
data0.plot(x=data0.x, y=data0.y, ax=axes[0,0],kind='scatter')
data1.plot(x=data1.x, y=data1.y, ax=axes[0,1],kind='scatter')
axes[0,0].set_title('title 0')
axes[0,1].set_title('title 1')

我不知道如何将轴[0,0]和[0,1]一起设置标题。我在文件里也找不到任何东西。为了达到这个目的,我不喜欢在乳胶漆的桌子上大惊小怪。有什么建议吗?在

抱歉,如果以前有人问过这个问题,我找不到任何东西,尤其是因为我不知道如何真正命名问题!在


Tags: 内容plottitlefig绘制图片axset
1条回答
网友
1楼 · 发布于 2024-09-27 09:23:58

使用fig.suptitle()设置图形标题,使用ax.set_title()设置轴(子图)标题非常简单。对于设置中间的、跨越列的标题,确实没有内置选项。在

解决这个问题的一种方法是在适当的位置使用^{}。我们需要为这个标题考虑一些额外的空间,例如使用^{}并找到这个figtext的适当位置。 在下面的示例中,我们使用标题所跨越的轴的边界框来找到一个集中的水平位置。垂直位置是最好的猜测。在

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.random.rand(10,8)

colors=["b", "g", "r", "violet"]
fig, axes = plt.subplots(nrows=2, ncols=4, sharex=True, sharey=True, figsize=(8,5)) 
#set a figure title on top
fig.suptitle("Very long figure title over the whole figure extent", fontsize='x-large')
# adjust the subplots, i.e. leave more space at the top to accomodate the additional titles
fig.subplots_adjust(top=0.78)     

ext = []
#loop over the columns (j) and rows(i) to populate subplots
for j in range(4):
    for i in range(2):
        axes[i,j].scatter(x, y[:,4*i+j], c=colors[j], s=25) 
    # each axes in the top row gets its own axes title
    axes[0,j].set_title('title {}'.format(j+1))
    # save the axes bounding boxes for later use
    ext.append([axes[0,j].get_window_extent().x0, axes[0,j].get_window_extent().width ])

# this is optional
# from the axes bounding boxes calculate the optimal position of the column spanning title
inv = fig.transFigure.inverted()
width_left = ext[0][0]+(ext[1][0]+ext[1][1]-ext[0][0])/2.
left_center = inv.transform( (width_left, 1) )
width_right = ext[2][0]+(ext[3][0]+ext[3][1]-ext[2][0])/2.
right_center = inv.transform( (width_right, 1) )

# set column spanning title 
# the first two arguments to figtext are x and y coordinates in the figure system (0 to 1)
plt.figtext(left_center[0],0.88,"Left column spanning title", va="center", ha="center", size=15)
plt.figtext(right_center[0],0.88,"Right column spanning title", va="center", ha="center", size=15)
axes[0,0].set_ylim([0,1])
axes[0,0].set_xlim([0,10])

plt.show()

enter image description here

相关问题 更多 >

    热门问题