1

In python, using matplotlib.pyplot, I am trying to save a plot. It is visible with plt.show() (it works how it is supposed to), but when I try to save it, using plt.savefig('file.png', bbox_inches = 'tight') (I tried with and without that bbox thing, because I found out it worked on someone else's similar problem. I also tried eliminating the grid, limits and all other atributes. I tested another x = y plot in the same folder and it worked and was visible) it saves a completly white image. (Sorry for the messy code)

import numpy as np
import matplotlib.pyplot as plt
import time
import random
import math

''' 0<theta<pi/2 si v0<30 ''' 
    #global constant variables#
scale = 1
g = -9.8#m/s^2
dt = 0.01 #heavy performance impact !(timestep>0)
t = 0#s
#input
initialvelocity = scale*float(input("initial velocity  :   "))
theta = float(input("theta  :   "))
    #initial conditions#
#speed_vector_decomposition
initialxvel = initialvelocity*math.cos(math.radians(theta))
initialyvel = initialvelocity*math.sin(math.radians(theta))
initialxpos = 0
initialypos = 0
xpos = initialxpos
ypos = initialypos
xposlist = []
yposlist = []
while ypos>=0:
    t+=dt
    xpos = initialxvel*t
    ypos = initialyvel*t+1/2*g*t*t
    xposlist.append(xpos)
    yposlist.append(ypos)
plt.plot(xposlist, yposlist)
plt.grid(True)
plt.xlabel('x (m) ')
plt.ylabel('y (m) ')
plt.title('2d motion')
plt.xlim(0, 100)
plt.ylim(0, 100)
plt.show()
#plt.plot([0, 1000], [0, 1000])
plt.savefig('test.png', bbox_inches='tight')
Zephyr
  • 11,891
  • 53
  • 45
  • 80

1 Answers1

1

Just change the places of savefig and show methods. The problem will be solved.

import numpy as np
import matplotlib.pyplot as plt
import time
import random
import math

''' 0<theta<pi/2 si v0<30 ''' 
    #global constant variables#
scale = 1
g = -9.8#m/s^2
dt = 0.01 #heavy performance impact !(timestep>0)
t = 0#s
#input
initialvelocity = scale*float(input("initial velocity  :   "))
theta = float(input("theta  :   "))
    #initial conditions#
#speed_vector_decomposition
initialxvel = initialvelocity*math.cos(math.radians(theta))
initialyvel = initialvelocity*math.sin(math.radians(theta))
initialxpos = 0
initialypos = 0
xpos = initialxpos
ypos = initialypos
xposlist = []
yposlist = []
while ypos>=0:
    t+=dt
    xpos = initialxvel*t
    ypos = initialyvel*t+1/2*g*t*t
    xposlist.append(xpos)
    yposlist.append(ypos)
plt.plot(xposlist, yposlist)
plt.grid(True)
plt.xlabel('x (m) ')
plt.ylabel('y (m) ')
plt.title('2d motion')
plt.xlim(0, 100)
plt.ylim(0, 100)

#plt.plot([0, 1000], [0, 1000])
plt.savefig('test.png')
plt.show()

Output:

enter image description here

Ahmet
  • 7,527
  • 3
  • 23
  • 47