0

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:

t_train = np.load('t_train.npy')
x_dot_test_computed = np.load('x_dot_test_computed.npy')
x_dot_test_predicted = np.load('x_dot_test_predicted.npy')

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()
2
  • 2
    Add bbox_inches='tight' to plt.savefig(..., bbox_inches='tight'). Commented May 14 at 17:08
  • 1
    As alluded to by Trenton, the thing is that Jupyter does some styling itself by default and one of those things is that bbox_inches='tight' is the setting. You have to specifically opt out of it, see bottom half here for an example of that. And so in your case, in Python you want it styled like you saw in Jupyter and so you need to add in those things that Jupyter handles itself.
    – Wayne
    Commented May 14 at 19:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.