Medulla Oblongata
Medulla Oblongata

Reputation: 3961

Python customised title and legend in figure

I am trying to show a legend near the top of my figure (like this) and a title above that (like this)

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,2850,3150,3400,3550,3800,3950,4050,4150,4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')
plt.text(0.5, 1.4, 'Data set A-1', 
        horizontalalignment='center', 
        fontsize=16,
        transform = ax.transAxes)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.25),
          ncol=3, fancybox=True, shadow=True)
#plt.tight_layout()
plt.show()

fig.savefig('test.pdf')

However, when I save this graph, both the title and legend are missing. Only the axes and datapoints are saved in the pdf.

Upvotes: 0

Views: 3047

Answers (2)

Adobe
Adobe

Reputation: 13477

Do You want the legend be on axes also?

enter image description here

#!/usr/bin/python3

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,
              2850,3150,3400,3550,3800,3950,4050,4150,
              4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')

ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)


ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True, shadow=True)
title = ax.set_title('Data set A-1')

fig.tight_layout()

fig.subplots_adjust(top=0.85)
title.set_y(1.07)

fig.savefig("13.png")

Upvotes: 1

tacaswell
tacaswell

Reputation: 87376

You are moving them out of the visible area. If you use set_title mpl will take care it's placement for you. Same with the bounding box on the legend:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,2850,3150,3400,3550,3800,3950,4050,4150,4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')
ax.set_title('Data set A-1')

ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)

ax.legend(loc='upper center', 
          ncol=3, fancybox=True, shadow=True)
#plt.tight_layout()
plt.show()

enter image description here

You probably also want to pass num_points=1 as a kwarg to legend.

Upvotes: 3

Related Questions