1

I've seen a couple examples but the plots are constructed differently and I don't see how to make the syntax work. Here's my code:

pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")
for i in range(0, len(list_of_data)):
  biorep = int(list_of_figure_key[i].split('.')[1])
  construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
  plot(time, list_of_data[i], color=color_dict[construct], linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )
  xlabel('time (hours)', fontsize=9)
  ylabel(ReadType, fontsize=9)
  xlim(min(time),max(time))
  legend(fontsize=8, loc='center left', bbox_to_anchor=(1, .5))
pdf_file.savefig()

It produces a beautiful figure but the legend is much too long and goes off the edge of the page. I'd like to shrink the plot on the x-axis so the legend will fit as a 2-column legend.

Figure can be seen here: https://i.stack.imgur.com/AuPsG.jpg

Thanks in advance!

user1539097
  • 109
  • 3
  • 8

1 Answers1

1

You can make a two-column legend using the ncol legend attribute. You can shrink the width of the plot by drawing the axis on the plot and fixing its size:

from matplotlib import pyplot as plt
fig = plt.figure()                      # initialize figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # add axis

To make this work with your code, something like this should work:

# import pyplot
from matplotlib import pyplot as plt

# set up filename to save it
pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")

# set up axis object
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# plot your data
for i in range(0, len(list_of_data)):
    biorep = int(list_of_figure_key[i].split('.')[1])
    construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
    ax.plot(time, list_of_data[i], color=color_dict[construct],
        linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )

# modify axis limits and legend 
ax.set_xlabel('time (hours)', fontsize=9)
ax.set_ylabel(ReadType, fontsize=9)
ax.set_xlim(min(time),max(time))
ax.legend(fontsize=8, loc='upper left', bbox_to_anchor=(1, .5), ncol=2)

# save final figure
plt.savefig(pdf_file)

In your code, you were remaking the legend, the limits and the legend at each iteration of the for-loop, as well as saving and then overwriting the pdf image. This isn't necessary -- you can just do it once at the end.

For more legend tips, this post is handy. This one is also helpful.

Community
  • 1
  • 1
rebeccaroisin
  • 573
  • 5
  • 9
  • @Ajean I've edited the response to fix the issues you mention -- let me know if there's anything else you think would improve it! – rebeccaroisin Sep 24 '14 at 12:09
  • @rebeccaroisin you're so accomadating, love it! And there's your upvote for your trouble – Ajean Sep 24 '14 at 14:12
  • @rebeccaroisin - thanks, the add_axes is what I was looking for. And also thanks for catching the loop, it now runs a bit faster. – user1539097 Sep 24 '14 at 22:31