1

Why am I getting a ValueError in matplotlib.pyplot ?. Here is my code:

import matplotlib.pyplot as plt

plt.plot([1,2,3,4,5,6])
f = 1.234
s = "number %i" % f
print s
plt.savefig(s)

so far so good. The figure is saved to a file with the name number 1 (the integer part of f) If however I do.

plt.plot([1,2,3,4,5,6])
f = 1.234
s = "number %.2f" % f
print s
plt.savefig(s)

The print statement prints 1.234 as expected whereas the plt.savefig(s) gives:

ValueError: Format "23" is not supported. Supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.

Somehow the savefig() method mixes the string formatting with the file format for saving. I am running python 2.7 with matplotlib 1.5.1

2
  • 2
    why not appending the filename extension anyway. Did you test that? I'm afraid that the '.' character in the float is corrupting the filename, but afaik this can't be helped with string formating, unless you are going to add some more code to ecxplicitly replace the '.' with another character like plt.savefig(s.replace('.',',')) Commented Feb 4, 2016 at 21:51
  • That's a good point I did not think about it. It works now thanks! Commented Feb 4, 2016 at 21:53

1 Answer 1

3

plt.savefig tries to guess the desired file format based on the filename extension. If the extension is not recognized, you get a ValueError.

You could either change the filename to include a recognized filename extension, or include the format parameter:

plt.savefig(s, format='png')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.