Matplotlib绘图未显示在保存的png图像上

2024-09-26 18:06:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,使用matplotlib.pyplot,我试图保存一个绘图。它在plt.show()中是可见的(它的工作方式应该是这样的),但是当我尝试保存它时,使用plt.savefig('file.png', bbox_inches = 'tight')(我尝试了使用和不使用bbox的东西,因为我发现它对其他人的类似问题有效。我还尝试了消除网格、限制和所有其他atributes。我测试了另一个x = y在同一个文件夹中打印,它工作并可见)它保存了一个完全白色的图像。(对不起,代码太乱了)

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')

Tags: importinputmatplotlibshowpltmathpyplottheta
1条回答
网友
1楼 · 发布于 2024-09-26 18:06:44

只需更改savefigshow方法的位置。这个问题会解决的

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()

输出:

enter image description here

相关问题 更多 >

    热门问题