0

I want to place my label on top of my plot in another box in Python. My existing plot looks as follows:

my plot

Here is my code:

fig = plt.figure()
plt.plot(t, sol[:,0], 'blue', lw = 3, label='$N$')
plt.plot(t, sol[:,1], 'green', lw = 3, label='$P$')
plt.plot(t, sol[:,2], 'red', lw = 3, label='$Z$')
plt.plot(t, sol[:,3], 'black', lw = 3, label='$Z$')
plt.legend(loc='best')
plt.xlabel('Time (days)', fontsize=10.)
plt.ylabel('$N,P,Z,D$ ($\mu$mol N L$^{-1}$)', fontsize=10.)
plt.xlim([0.,365.*sim_years])
plt.ylim([0,16])
plt.xticks(fontsize=10.)
plt.yticks(fontsize=10.)
plt.grid()
plt.show()

I want a label to look like this:

Expected label

2 Answers2

0

The title of this post is a little bit misleading.

I guess this what you're after: http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html

TomR8
  • 102
  • 4
0

You could experiment with using the bbox_to_anchor parameter to plt.legend(). This gives you extra control over the location:

import matplotlib.pyplot as plt
import numpy as np

# Demo data
sol = np.array([[3,3,4,3], [1,4,2,7], [2,5,3,10], [3,6,4,15], [5,8,2,14]])
t = [100, 200, 300, 400, 500]

fig = plt.figure()
plt.plot(t, sol[:,0], 'blue', lw = 3, label='$N$')
plt.plot(t, sol[:,1], 'green', lw = 3, label='$P$')
plt.plot(t, sol[:,2], 'red', lw = 3, label='$Z$')
plt.plot(t, sol[:,3], 'black', lw = 3, label='$Z$')
plt.legend(loc='upper center', ncol=4, bbox_to_anchor=(0.5, 1.1))
plt.xlabel('Time (days)', fontsize=10.)
plt.ylabel('$N,P,Z,D$ ($\mu$mol N L$^{-1}$)', fontsize=10.)
#plt.xlim([0.,365.*sim_years])
plt.ylim([0,16])
plt.xticks(fontsize=10.)
plt.yticks(fontsize=10.)
plt.grid()
plt.show()

This would display as follows:

Demo plot with legend external to the plot

Here bbox_to_anchor=(0.5, 1.1) means half way along horizontally, with 1.0 being at the top, so 1.1 being just above the top. ncols=4 is used to make it display horizontally.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • Thanks Martin. It works, I really appreciate your response, sorry that the title of my post was a little bit misleading, but thanks for understanding. – Okolie Austine Frank Dec 22 '16 at 17:16
  • You're welcome. Don't forget to click on the grey tick under the up/down arrow to accept an answer as the solution. – Martin Evans Dec 22 '16 at 17:24