Reputation: 341
I've written some code to produce a multi-panelled figure in matplotlib. To make the figure look sharper for use in a document, I tried increasing the dpi. I found, though, that this also changed the sizes of the figure, font, lines etc., as illustrated in the following simpler example:
#First normal figure
fig, axarr = plt.subplots(2,2, figsize=(6,6))
for i,ax in enumerate(axarr.flatten()):
ax.plot(range(10))
ax.set_title('title'+str(i), fontsize=10)
ax.set_xlabel('x'+str(i), fontsize=10)
ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
#Again, with higher dpi
fig, axarr = plt.subplots(2,2, figsize=(6,6), dpi=200)
for i,ax in enumerate(axarr.flatten()):
ax.plot(range(10))
ax.set_title('title'+str(i), fontsize=10)
ax.set_xlabel('x'+str(i), fontsize=10)
ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
plt.show()
On my computer (using matplotlib 1.4.3), the second figure is larger in size and the text is larger, so that the y-axis labels overlap. Without the use of plt.tight_layout(), the overlap of the subplot axes is also worse. Obviously, this is not helpful when just trying to make a higher quality figure. What is going on here, and how can I change the figure quality and keep the appearance of the figure constant? Is there a solution that will also work when I've adjusted subplot parameters, added colour bars and legends etc. i.e. in general? Thanks in advance for any help you can give.
Upvotes: 3
Views: 13939
Reputation: 1307
Your problem is that you show it and then you save it on the GUI window. You have to save image from command savefig
defining there the dpi.
Something like this:
import matplotlib.pyplot as plt
#First normal figure
fig, axarr = plt.subplots(2,2, figsize=(6,6))
for i,ax in enumerate(axarr.flatten()):
ax.plot(range(10))
ax.set_title('title'+str(i), fontsize=10)
ax.set_xlabel('x'+str(i), fontsize=10)
ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
plt.savefig('myfigure_100.png', dpi=100)
plt.savefig('myfigure_200.png', dpi=200)
If you want to show it, you can at the end of the scrpit add plt.show()
EDIT
The relation of the dpi of figure size and the font size can be shown on the following example:
import matplotlib.pyplot as plt
#First normal figure
fig1, axarr1 = plt.subplots(2,2, figsize=(6,6), dpi=100)
for i,ax in enumerate(axarr1.flatten()):
ax.plot(range(10))
ax.set_title('title'+str(i), fontsize=10)
ax.set_xlabel('x'+str(i), fontsize=10)
ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
fig2, axarr2 = plt.subplots(2,2, figsize=(12,12), dpi=50)
for i,ax in enumerate(axarr2.flatten()):
ax.plot(range(10))
ax.set_title('title'+str(i), fontsize=20)
ax.set_xlabel('x'+str(i), fontsize=20)
ax.set_ylabel('y'+str(i), fontsize=20)
plt.tight_layout()
plt.show()
Upvotes: 7