I am plotting a graph with 3 y axis, and it shows in the plot window of Spyder instead of saving correctly in a folder. The graph saved in a folder is blank. Here's my code :
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
plt.figure(figsize = (121, 75))
ax1.set_xlabel('time(s)')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')
ax3.set_ylabel('y3')
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.15))
plt.xticks(fontsize=50)
plt.yticks(fontsize=50)
ax1.plot(fd[fd.columns[0]], fd[fd.columns[1]], color = 'r', linewidth = 2)
ax2.plot(fd[fd.columns[0]], fd[fd.columns[2]], color = 'g', linewidth = 2)
ax3.plot(fd[fd.columns[0]], fd[fd.columns[3]], color = 'b', linewidth = 2)
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]], ['y1', 'y2', 'y3'])
plt.savefig(folder "/" str(file_name) "y1/2/3.png")
plt.close()
Am I doing something wrong here ? I don't call the show()
function so I don't understand why the graph shows anyway (when plotting the 3 y axis on the same graph with only using plt.figure()
, plt.plot()
then plt.save()
and close()
, it works as intended)
Edit : What I want is to have the graph saved correctly in my folder, with the size I set in plt.figure()
, which isn't the case now.
CodePudding user response:
I found what went wrong :
I stead of writing
fig = plt.figure(figsize=(121, 75)) fig, ax1 = plt.subplots()
,
I had to write
fig, ax1 = plt.subplots(figsize=(121, 75))
The graph then plots at the size indicated, and doesn't shows in the window of Spyder.
CodePudding user response:
You can use set_size_inches
before saving the figure. dpi
feature can be use to increase the resolution of the figure also.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.size'] = '50'
fig = plt.figure(figsize=(121, 75), dpi=200)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax1.set_xlabel('time(s)')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')
ax3.set_ylabel('y3')
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.05))
rspine2 = ax2.spines['right']
rspine2.set_position(('axes', 1.0))
# plt.xticks(fontsize=50)
# plt.yticks(fontsize=50)
ax1.plot(np.arange(100), np.random.rand(100), color='r', linewidth=2)
ax2.plot(np.arange(100), np.random.rand(100), color='g', linewidth=2)
ax3.plot(np.arange(100), np.random.rand(100), color='b', linewidth=2)
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]], ['y1', 'y2', 'y3'])
# fig.tight_layout()
figure = plt.gcf()
figure.set_size_inches(121, 75)
plt.savefig("3.png", dpi=None)
plt.close()