Change figure size and figure format in matplotlib

Question:

I want to obtain fig1 exactly of 4 by 3 inch sized, and in tiff format correcting the program below:

import matplotlib.pyplot as plt

list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]

plt.plot(list1, list2)
plt.savefig('fig1.png', dpi = 300)
plt.close()
Asked By: golay

||

Answers:

The first part (setting the output size explictly) isn’t too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I’m not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick’s convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong 😉

Answered By: mgilson

You can set the figure size if you explicitly create the figure with

plt.figure(figsize=(3,4))

You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don’t know if any of matplotlib backends support tiff

Answered By: Francesco Montesano

You can change the size of the plot by adding this before you create the figure.

plt.rcParams["figure.figsize"] = [16,9]
Answered By: ghosh'.

If you need to change the figure size after you have created it, use the methods

fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)

where value_height and value_width are in inches. For me this is the most practical way.

Answered By: Antoni