如何使 Matplotlib 标题以图形和图外图例框为中心

问题描述 投票:0回答:1

我有一个图表,图例之外有图例。我的标题位于图表的中心,并且我想保持其居中。问题是,标题仅以图表为中心,而不是以图表和图例为中心。所以这让我的情节总是看起来有偏差: [1]:https://i.stack.imgur.com/dOlpS.png

有没有办法将图表移到一边,以便标题显示在两者的中心?

最小复制:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x,y1)
plt.plot(x,y2)
plt.title("A very long title that makes the graph shorter than the title itself, it's so long it makes me sick to the core")
plt.legend(["sin x", "cos x"], bbox_to_anchor = [1,0.5], loc = "center left", fontsize = 20)
plt.show()
python matplotlib
1个回答
0
投票

您的方法相当于在 matplotlib 的对象框架中执行以下操作。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(constrained_layout=True)

ax.plot(x,y1)
ax.plot(x,y2)
ax.legend(["sin x", "cos x"], bbox_to_anchor = [1,0.5], loc = "center left", fontsize = 20)
ax.set_title("A very long title that makes the graph shorter than the title itself,\n it's so long it makes me sick to the core.\n")

基本上,标题被分配给实际的绘图(ax 对象)。您的要求是将标题分配给整个图像,其中包含绘图和图例(即图形对象)。这将是新的结果。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(constrained_layout=True)

ax.plot(x,y1)
ax.plot(x,y2)
ax.legend(["sin x", "cos x"], bbox_to_anchor = [1,0.5], loc = "center left", fontsize = 20)
fig.suptitle("A very long title that makes the graph shorter than the title itself,\n it's so long it makes me sick to the core.\n")

© www.soinside.com 2019 - 2024. All rights reserved.