使用twiny时Python Matplotlib图形标题与轴标签重叠

2024-06-01 12:10:52 发布

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

我试图用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轴上的轴标签重叠,因此很难辨认(我想在这里发布一个图片示例,但我还没有足够高的重复率)。

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


Tags: 标题plotfigaxgeoxysetday
3条回答

忘记使用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()

enter image description here

ax.set_title('My Title\n', fontsize="15", color="red")
plt.imshow(myfile, origin="upper")

如果将'\n'放在标题字符串的正后方,则在标题的正下方绘制绘图。这可能也是一个快速的解决方案。

我不确定它是否是matplotlib的新版本中的一个新功能,但至少对于1.3.1来说,这只是:

plt.title(figure_title, y=1.08)

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

相关问题 更多 >