Change figure size and figure format in matplotlib

PythonPython 2.7Python 3.xMatplotlib

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

plt.rcParams["figure.figsize"] = [16,9]

Solution 3 - Python

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 ;-)

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongolayView Question on Stackoverflow
Solution 1 - PythonFrancesco MontesanoView Answer on Stackoverflow
Solution 2 - Pythonghosh'.View Answer on Stackoverflow
Solution 3 - PythonmgilsonView Answer on Stackoverflow
Solution 4 - PythonAntoniView Answer on Stackoverflow