Hamidreza Hamidreza - 1 month ago 18
Python Question

Save figure with its frame, matplotlib

How should I save a figure containing also its frame?

From this code;



import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib as mpl

my_list = [random.uniform(0.75, 1.25) for i in range(1000)]

mpl.rcParams['axes.linewidth'] = 2.5
my_fig = plt.figure(num=None, figsize=(12, 7), linewidth=5, facecolor='gold', edgecolor='gray')

plt.plot(my_list, label = 'My label',color = 'r', lw = 2.5)

plt.grid()
plt.gca().invert_xaxis()

plt.legend(loc='upper right', fontsize=14)
plt.ylabel('\n Y_axis [kPa] \n\n',fontsize=14)
plt.xlabel('\n X_axis [w] \n',fontsize=14)
plt.ylim([0,2])
plt.tick_params(axis='x', labelsize=12)
plt.tick_params(axis='y', labelsize=12)

plt.savefig("test.png")

plt.show()


I expect this figure;



enter image description here

But I get it without frame;



enter image description here

Where I'm wrong?


Answer

savefig will not honour the figure's face and edge colors but you can set them explicitly in the call.

plt.savefig('test.png', facecolor=my_fig.get_facecolor(),         
            edgecolor=my_fig.get_edgecolor())
Comments