Move figure title with matplotlib

2

I am using matplotlib, I have to make a figure with a second x-axis (above the figure), that worked for me with the following code. But when I want to title the figure, it overlays with the name of the top axis. Does anyone know how to solve this in this code? (I have searched for solutions on the web but since I am new to python I do not know how to implement them)

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

plt.title('Linea H2')

ax1.plot(radioarc, mcv1,'ko')
ax1.set_xlim(-1.65, 1.65)
ax1.set_xlabel("Radius[arcsec]")
ax1.set_ylabel("Velcidad Radial[km/s]")
plt.errorbar(radioarc, mcv1, yerr=sdv1, fmt='None', ecolor='k')

ax2 = ax1.twiny()
ax2.set_xlabel("Radius[pc]")
ax2.set_xlim(-1.65, 1.65)
ax2.set_xticks([-1.48, -1, -0.5, 0,0.5, 1, 1.48])
ax2.set_xticklabels(['-90','-60', '-30', '0', '30', '60', '90'])

plt.show()
    
asked by Gaia 31.07.2017 в 22:23
source

1 answer

0

You can place the axes where it suits you best to leave space for other elements. Retouching a bit the code you have put:

import numpy as np
import matplotlib.pyplot as plt


mcv1 = np.random.randn(10)
radioarc = np.arange(len(mcv1))

fig = plt.figure()
ax1 = fig.add_axes((0.1, 0.1, 0.5, 0.5)) # Añado unos 'axes' indicando la 
                                         # posición que quiero que ocupe 
                                         # dentro de la figura. 
                                         # Juega con estos valores

fig.suptitle('Linea H2') # en lugar de usar el 'title' del 'axes' uso 
                         # el 'suptitle' de la 'figure'

ax1.plot(radioarc, mcv1,'ko')
ax1.set_xlim(-1.65, 1.65)
ax1.set_xlabel("Radius[arcsec]")
ax1.set_ylabel("Velcidad Radial[km/s]")

ax2 = ax1.twiny()
ax2.set_xlabel("Radius[pc]")
ax2.set_xlim(-1.65, 1.65)
ax2.set_xticks([-1.48, -1, -0.5, 0,0.5, 1, 1.48])
ax2.set_xticklabels(['-90','-60', '-30', '0', '30', '60', '90'])

fig.show()

The result would be something like the following:

As you can see there is enough space between the title of the figure and the title of the upper X axis. Adjust it as you consider.

    
answered by 09.08.2017 в 17:16