首页 > 解决方案 > Matplotlib 故障 [python3]

问题描述

大家好,我正在尝试制作一个简单的 matplotlib 图形函数来表示电容器的充电和放电功能。这是程序:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

import math

x_data = [0] # storing the variable values
y_data = [0] # storing the dependent variable value

fig, ax = plt.subplots() # creating a subplot and its axes
ax.set_xlim(0, 20) # setting the x axe limits
ax.set_ylim(0, 12) # setting the y axe limits
line, = ax.plot(0, 0) # create a line object

# creating an function to animate
def animation_frame(t):

    x_data.append(t) # append the variable to x_data arrya

    # print a sort of differential of the function
    print(y_data[len(y_data) - 1] - y_data[len(y_data) - 2])

    # check if the differential is so small that can be considered as 0 (local maximum point)
    if y_data[len(y_data) - 1] - y_data[len(y_data) - 2] >= 0.0012 or y_data[len(y_data) - 1] - y_data[len(y_data) - 2] == 0.0:

        # if it isn't continue plotting the charging function
        y_data.append(9 * ( 1 - (np.e)**(-(t/(180000*0.00001)))))

    else:
        # plot the discharging function
        y_data.append(9 * (np.e)**(-(t/(180000*0.00001))))

    # set the line points coordinates
    line.set_xdata(x_data)
    line.set_ydata(y_data)

run the animation function 
animation = FuncAnimation(fig, func=animation_frame, frames=np.arange(0, 10, 0.05), interval=10)

# show the plot
plt.show()

函数类型并不重要,因为即使在 if-else 子句的 else 中(在 animate 函数中)我插入了一个简单的标识 (f(t) = t),它也不起作用并且会出现故障,这里有一些图像:

使用 f(t) = t 函数的最终故障

使用 f(t) = V0 * e^(-t/RC) 放电函数的最终毛刺

我怀疑问题出在差异检查部分,在动画功能中......但我不知道如何解决它。你有什么想法?

标签: python-3.xfunctionmatplotlibplot

解决方案


推荐阅读