163

我正在尝试使用 twiny 在同一个图表上绘制两个单独的数量,如下所示:

fig = figure()
ax = fig.add_subplot(111)
ax.plot(T, r, 'b-', T, R, 'r-', T, r_geo, 'g-')
ax.set_yscale('log')
ax.annotate('Approx. sea level', xy=(Planet.T_day*1.3,(Planet.R)/1000), xytext=(Planet.T_day*1.3, Planet.R/1000))
ax.annotate('Geostat. orbit', xy=(Planet.T_day*1.3, r_geo[0]), xytext=(Planet.T_day*1.3, r_geo[0]))
ax.set_xlabel('Rotational period (hrs)')
ax.set_ylabel('Orbital radius (km), logarithmic')
ax.set_title('Orbital charts for ' + Planet.N, horizontalalignment='center', verticalalignment='top')


ax2 = ax.twiny()
ax2.plot(v,r,'k-')
ax2.set_xlabel('Linear speed (ms-1)')

show()

并且数据显示得很好,但我遇到的问题是图形标题与辅助 x 轴上的轴标签重叠,因此几乎无法辨认(我想在这里发布一个图片示例,但我没有足够高的代表了)。

我想知道是否有一种简单的方法可以将标题直接向上移动几十个像素,以便图表看起来更漂亮。

4

7 回答 7

284

我不确定它是否是 matplotlib 更高版本中的新功能,但至少对于 1.3.1,这很简单:

plt.title(figure_title, y=1.08)

这也适用于plt.suptitle(),但(还)不适用于plt.xlabel()等。

于 2014-04-28T10:14:27.430 回答
36

忘记使用plt.title,直接用 . 放置文本plt.text。下面给出一个过于夸张的例子:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         horizontalalignment='center',
         fontsize=20,
         transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])

plt.show()

在此处输入图像描述

于 2012-10-05T17:28:12.197 回答
16

我遇到了与子图标题重叠的 x-label 问题;这对我有用:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].scatter(...)
ax[1].scatter(...)
plt.tight_layout()
.
.
.
plt.show()

在此处输入图像描述

在此处输入图像描述

参考:

于 2018-07-05T05:56:29.550 回答
11
ax.set_title('My Title\n', fontsize="15", color="red")
plt.imshow(myfile, origin="upper")

如果你把'\n'你的标题字符串,情节就在标题下方绘制。这也可能是一个快速的解决方案。

于 2017-09-29T06:53:17.950 回答
11

您可以在这种情况下使用 pad:

ax.set_title("whatever", pad=20)
于 2020-03-27T20:13:42.207 回答
4

plt.tight_layout()之前用过plt.show()。它运作良好。

于 2018-08-24T06:10:59.793 回答
0

如果您不想进入标题的x,位置,这是一个临时解决方案。y

以下为我工作。

plt.title('Capital Expenditure\n') # Add a next line after your title

荣誉。

于 2021-02-06T15:10:45.857 回答