I am encountering issues with my plotting code when running it as a Python script in PyCharm. The plots overlap, and the legends are not displayed, which does not happen when I run the same code in a Jupyter notebook. I need to save numerous plots automatically after running multiple Python scripts.
Below is the link to my data for plotting:
link of my data
Attached are the code and the files in question.
Could you please advise on how to resolve these issues?
This is the code:
num_columns = x_dot_test_computed.shape[1]
# fig, axs = plt.subplots(num_columns, 1, figsize=(9,10), sharex=True)
fig, axs = plt.subplots(num_columns, 1, sharex=True)
# If only one column, axs may not be an array, handle this case:
if num_columns == 1:
axs = [axs] # Make it iterable
for i in range(num_columns):
# Plot each column of data
axs[i].plot(t_train, x_dot_test_computed[:, i], "b-", label="Computed" if i == 0 else "_nolegend_")
axs[i].plot(t_train, x_dot_test_predicted[:, i], "r-", label="Predicted" if i == 0 else "_nolegend_")
axs[i].set_ylabel(r"$dot x_{}$".format(i))
# Set common x-label
axs[-1].set_xlabel("Time (t)")
# Adding a single legend for the entire figure, outside the last subplot
fig.legend(loc="lower center", bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
# Adjust layout to prevent overlap and make sure everything fits well
plt.tight_layout()
# Adjust the bottom margin to make space for the legend
plt.subplots_adjust(bottom=0.2)
plot_dir = 'SavedPlots'
if not os.path.exists(plot_dir):
os.makedirs(plot_dir)
# Save the figure in PDF and PNG format with high resolution
plt.savefig(f'{plot_dir}/plot_high_res1.pdf', format='pdf', dpi=300)
plt.savefig(f'{plot_dir}/plot_high_res1.png', format='png', dpi=300)
# Show the plot
plt.show()