0

I´m a noobie with python, but I discover that with vscode I can´t save plots, but if I run the same code with Spyder the plot is saved to the path where the script is. Is there an option that I need to activate in VScode?

Example code:

import matplotlib.pyplot as plt
  
# creating plotting data
xaxis =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
yaxis =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  
# plotting 
plt.plot(xaxis, yaxis)
plt.xlabel("X")
plt.ylabel("Y")
  
# saving the file.Make sure you 
# use savefig() before show().
plt.savefig("squares.png", format="png")
  
plt.close()
amotoli
  • 39
  • 7
  • VSCode is likely saving your plot fine, just somewhere else. Search your computer for `squares.png`. Also, look into: https://stackoverflow.com/questions/56776521/python-in-vscode-set-working-directory-to-python-files-path-everytime – K.Cl Jun 20 '22 at 20:05
  • This code works in VSCode for me. Use os.getcwd() to confirm current working directory. – stan61285 Jun 20 '22 at 20:09
  • Thank you @K.Cl .. You were right. I thought that the default saving path was the same path as the script.. How can I change the path to be the same as the script for Vscode? – amotoli Jun 20 '22 at 20:14
  • I mean, I'm just quoting answers from the list I gave you. Try: `File > Preferences > Settings and Search for "Execute in File Path"`. – K.Cl Jun 20 '22 at 20:35

1 Answers1

0

I tested with the latest version of VS Code and a previous historical version and restored all settings to default.

The code you show all generates squares.png in my current working directory.

enter image description here

So please make sure that you are running this code file in the workspace, not just open this code file with VS Code, because then VS Code will not be able to find your working environment.

After testing, if you just open this code file in VS Code, the picture will be generated in your computer user folder.For me it was in C:\Users\Admin

JialeDu
  • 6,021
  • 2
  • 5
  • 24