matplotlib 从数据框绘制散点图gif

ux6nzvsh  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(157)

我有一个包含6行和4列数据的数据框。有没有办法生成gif散点图(y是不同颜色的4列,x是索引行)图,其中在gif的每一帧中,列1的第一数据点及其第一相应行数据以不同颜色相对于共享x轴(索引)绘制,同时,列2,绘制第3和第4个数据点,并逐步进行,直到绘制所有列的最后第6个点?如果GIF根本不可能,是否有任何其他方法可以生成至少一个电影,以便我可以包括在我的ppt幻灯片中?我感谢您的任何反馈!我得到的错误是生成一个空图,并说:TypeError:无法解压缩不可迭代的AxesSubplot对象。但我不确定这是否会阻止绘制结果。
这是我的数据和代码工作的一个示例:

import pandas as pd
import numpy as np

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
from itertools import count
from IPython import display


row_data = np.arange(0, 6)
column_X = np.random.rand(6,)
column_Y = np.random.rand(6,)
column_Z = np.random.rand(6,)
column_K = np.random.rand(6,)

my_df = pd.DataFrame()
my_df['column_X'] = column_X
my_df['column_Y'] = column_Y
my_df['column_Z'] = column_Z
my_df['column_K'] = column_K
my_df.index = row_data
my_df['index'] = row_data


def animate(j):
    fig, ax = plt.subplot(sharex= True)
    ax[1]=my_df['column_X', color = 'blue']
    ax[2]=my_df['column_Y', color = 'red']
    ax[3]=my_df['column_Z', color = 'brown']
    ax[4]=my_df['column_K', color = 'green']
    y=my_df['index']
    x.append()
    y.append()
    plt.xlabel(color = 'blue')
    plt.ylabel(color = 'red')
    ax.set_ylabel("progressive sales through time")
    ax.set_xlabel("progressive time")
    plt.plot(x,y)
    
animation_1 = animation.FuncAnimation(plt.gcf(),animate,interval=1000)
plt.show()

# Inside Jupyter:

video_1 = animation_1.to_html5_video()
html_code_1 = display.HTML(video_1)
display.display(html_code_1)
plt.tight_layout()
plt.show()
6ie5vjzr

6ie5vjzr1#

问得好!matplotlib动画可能很棘手。我在这个问题上有点纠结,主要是因为你想为不同的列使用不同的颜色。你需要4个不同的Line 2D对象来完成这个任务。

# VSCode notebook magic
%matplotlib widget

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

my_df = pd.DataFrame()
my_df["column_X"] = np.random.rand(6)
my_df["column_Y"] = np.random.rand(6)
my_df["column_Z"] = np.random.rand(6)
my_df["column_K"] = np.random.rand(6)

fig, ax = plt.subplots()
# four y-data lists, x-data is shared
xdata, y1, y2, y3, y4 = [], [], [], [], []
# four Line3D objects with different colors
graph1, = ax.plot([], [], 'ro-')
graph2, = ax.plot([], [], 'go-')
graph3, = ax.plot([], [], 'bo-')
graph4, = ax.plot([], [], 'ko-')
# set up the plot
plt.xlim(-1, 6)
plt.xlabel('Time')
plt.ylim(0, 1)
plt.ylabel('Price')

# animation function
def animate(i):
    xdata.append(i)
    y1.append(my_df.iloc[i,0])
    y2.append(my_df.iloc[i,1])
    y3.append(my_df.iloc[i,2])
    y4.append(my_df.iloc[i,3])
    graph1.set_data(xdata, y1)
    graph2.set_data(xdata, y2)
    graph3.set_data(xdata, y3)
    graph4.set_data(xdata, y4)
    return (graph1,graph2,graph3,graph4,)

anim = animation.FuncAnimation(fig, animate,  frames=6, interval=500, blit=True)
anim.save('test.mp4')
#plt.show()

下面是生成的.gif文件(使用Adobe Express从.mp4转换而来):

相关问题