Python Matlab动态演示GIF

# 以下代码在sublime text3中运行以显示自己进行数据处理后的效果(pycharm和jupyter都不能显示动图,可能是因为图片嵌入的原因)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as mpatches


def init():
    # 要根据不同的数据来修改该图的坐标上下限的位置
    ax.set_xlim(-15, 40)
    ax.set_ylim(-15, 40)
    return ln,


def update(frame):
    xdata.append(data['PosX'][frame])
    ydata.append(data['PosY'][frame])
    # 在该图片中只保存70个轨迹点
    # if len(xdata) > 200:
    #     del xdata[:-70]
    #     del ydata[:-70]
    ln.set_data(xdata, ydata)
    return ln,


def data_gen():
    step = 1
    for frame in range(len(data) - 1):
        print(frame*100/(len(data) - 1), "%")
        frame += step
        yield frame
        continue


if __name__ == '__main__':
    fig, ax = plt.subplots()
    xdata, ydata = [], []
    ln, = ax.plot([], [], 'r-', animated=False, linewidth=0.5)
    data = pd.read_csv(
        r'D:\SJTU大三(上)总\NA322船舶与海洋工程自主创新实验\个人报告\data\Group3.csv', sep=',')

    xy1 = np.array([15, 10])
    xy2 = np.array([20, 18])
    xy3 = np.array([10, 30])

    circle1 = mpatches.Circle(xy1, 2, color="r", alpha=0.5, label='1')
    ax.add_patch(circle1)
    circle2 = mpatches.Circle(xy2, 2, color="b", alpha=0.5, label='2')
    ax.add_patch(circle2)
    circle3 = mpatches.Circle(xy3, 2, color="y", alpha=0.5, label='3')
    ax.add_patch(circle3)
    ax.set_xlabel('x_axis(m)')
    ax.set_ylabel('y_axis(m)')

    ani = FuncAnimation(fig, update, frames=data_gen, interval=0.1, repeat=False,
                        init_func=init, blit=True)
    ani.save(r'D:\SJTU大三(上)总\NA322船舶与海洋工程自主创新实验\研究进度\第18周_动态演示\gif\disanzu.gif',
             writer='pillow')

    plt.legend()
    plt.show()
    ax.set_aspect('equal', 'datalim')

    print('Saved')
    plt.close()
    # 最后可以加一行代码让动图变成gif文件保存
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from ani_test_api import *


target_path = "D:/SJTU大三(上)总/NA322船舶与海洋工程自主创新实验/研究进度/第18周_动态演示/gif format/"
target_name = "pendulum.gif"
target_full = target_path + target_name


g = 9.8
l = 1
theta_0 = [0, 3]  # theta初值
t = np.linspace(0, 3, 50)

# solving 常微分方程
theta = odeint(mode1, theta_0, t, args=(g, l))

fig1 = plt.figure(figsize=(5, 5))
ax = fig1.add_subplot(1, 1, 1, facecolor='black')
plt.rcParams['font.size'] = 15

ims = []  # 将每一帧都存进去
for i in range(len(theta)):
    ln, = ax.plot([0, np.sin(theta[i, 0])], [0, -np.cos(theta[i, 0])], color='white', lw=2)
    bob, = ax.plot(np.sin(theta[i, 0]), -np.cos(theta[i, 0]), 'o', markersize=20, color='yellow')
    tm = ax.text(-0.9, 0.25, 'Time = %.1fs' % t[i], color='white')
    # save_my_images(i)
    ims.append([ln, bob, tm])
    print(i*100/len(theta), "%")

ax.set_aspect('equal', 'datalim')
# ax.set_aspect('equal')

ani = animation.ArtistAnimation(fig1, ims, interval=10, repeat=False)  # 生成动画

# 保存成gif
ani.save(target_full, writer='pillow')
print("Saved")
plt.draw()
print("Drew")
plt.pause(3)
print("Paused")
plt.close(fig1)
print("Closed")
import math


def save_my_images(i_save_my_images):
    target_images_path = "D:/SJTU大三(上)总/NA322船舶与海洋工程自主创新实验/研究进度/第18周_动态演示/png format/"
    target_images_name = "pendulum_"
    target_images_name += str(i_save_my_images)
    target_images_name += ".png"
    target_images_full = target_images_path + target_images_name
    plt.savefig(target_images_full)


# defining the function for 常微分方程
def mode1(theta, t, g, l):
    theta1 = theta[0]
    theta2 = theta[1]
    dtheta1_dt = theta2
    dtheta2_dt = - (g / l) * math.sin(theta1)
    dtheta_dt = [dtheta1_dt, dtheta2_dt]
    return dtheta_dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as m_patches

if __name__ == '__main__':
    target_path = "D:/SJTU大三(上)总/NA322船舶与海洋工程自主创新实验/研究进度/第18周_动态演示/gif format/"
    target_name = "py_plot_pos.gif"
    target_full = target_path + target_name
    fig1 = plt.figure(1)  # 创建画布
    ax = fig1.add_subplot(1, 1, 1, facecolor='white')  # 创建子图
    plt.rcParams['font.size'] = 15
    ax.set_xlim(-15, 40)
    ax.set_ylim(-15, 40)  # 设置子图上下限

    xy1 = np.array([15, 10])
    xy2 = np.array([20, 18])
    xy3 = np.array([10, 30])  # 目标点

    circle1 = m_patches.Circle(xy1, 2, color="r", alpha=0.5, label='1')
    ax.add_patch(circle1)
    circle2 = m_patches.Circle(xy2, 2, color="b", alpha=0.5, label='2')
    ax.add_patch(circle2)
    circle3 = m_patches.Circle(xy3, 2, color="y", alpha=0.5, label='3')
    ax.add_patch(circle3)  # 画目标区域

    ax.set_xlabel('x_axis(m)')
    ax.set_ylabel('y_axis(m)')  # 坐标轴符号
    # plt.legend()

    ims = []  # 将每一帧都存进去
    data_frame = pd.read_csv(
        r'D:\SJTU大三(上)总\NA322船舶与海洋工程自主创新实验\个人报告\data\Group3.csv', sep=',')
    data_posx = data_frame['PosX'].values
    data_posy = data_frame['PosY'].values

    max_num = 150  # 帧数
    step_over = round(len(data_posx) / max_num)  # 步长

    for i_row in range(max_num):
        i_row += 1
        posx_tmp = data_posx[1:i_row*step_over+step_over]
        posy_tmp = data_posy[1:i_row * step_over + step_over]
        ln, = ax.plot(posx_tmp, posy_tmp, 'r-')
        ims.append([ln])
        print(i_row/max_num*100, "%")

    ax.set_aspect('equal')
    ani = animation.ArtistAnimation(fig1, ims, interval=10, repeat=False)  # 生成动画
    ani.save(target_full, writer='pillow')

    print("Saved")
    plt.draw()  # 显示图
    print("Drew")
    plt.pause(5)  # 暂停2秒
    print("Paused")
    # plt.close(fig1)  # 自动关闭
    print("Closed")

 

 

 

 

clear all; clc; %position_movie

position_xy = importdata('D:\SJTU大三(上)总\NA322船舶与海洋工程自主创新实验\个人报告\data\Group3.csv'); %读取原始文件
position_xy = position_xy.data(:,[5 6]); %提取位置信息

x0 = [ 15 20 10 ]; y0 = [ 10 18 30 ]; %设置目标点
r=2; theta=0:pi/100:2*pi; text_size = 8;

figure %新建一张图
set(gca, 'xlim', [-15 40], 'ylim', [-15 40]); hold on; %定义坐标轴的范围

for i_num = 1 : 3 %绘制目标区域
    x = x0(1,i_num) + r * cos(theta);
    y = y0(1,i_num) + r * sin(theta);
    plot(x,y, '-g'); hold on;
end
text(x0(1,1)-0.5,y0(1,1),'A', 'FontSize',text_size);text(x0(1,2)-0.5,y0(1,2),'B', 'FontSize',text_size);text(x0(1,3)-0.5,y0(1,3),'C', 'FontSize',text_size);
text(position_xy(1,1)-0.5,position_xy(1,2),'Start', 'FontSize',text_size);
clear x0 y0 r theta text_size i_num x y;

max_num = 400; %帧数
step_over = round(size(position_xy,1)/max_num);  %步长
for i_num = 1 : max_num
    position_temp = position_xy( (i_num-1) * step_over + 1 : i_num * step_over + step_over, :); %提取一帧内要画的轨迹
    plot(position_temp(:,1), position_temp(:,2), '-r'); %绘制一帧
    clear position_temp;
    hold on
    
    frame = getframe(gcf);  %创造一帧
    im = frame2im(frame); %转成图像
    [I,map] = rgb2ind(im,20); %将RGB图像转换为索引图像     
    if i_num == 1
        imwrite(I,map,'plot_position.gif','gif', 'Loopcount',inf,'DelayTime',0.001);%创建gif
    elseif i_num == max_num
        imwrite(I,map,'plot_position.gif','gif','WriteMode','append','DelayTime',0.001);
    else
        imwrite(I,map,'plot_position.gif','gif','WriteMode','append','DelayTime',0.001);
    end
    clear I map frame im;
end
clear max_num step_over i_num;
close all;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穿越前列线打造非凡yt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值