- Create an animated graph by inputting np.array (time series data)

```
import pandas as pd
import numpy as np
import plotly.express as px
def create_animation_graph(input_array: np.array, start: str = '1900-01-01 0:00', g_type: str = 'line', y_label: str = 'value',
x_label: str = 'time') -> object:
"""
np.Entering an array returns a plotly animated graph
:param input_array:Data np.array
:param start:Start time
:param g_type:Graph type'line','bar','area','scatter'
:param y_label:y-axis name
:param x_label:x-axis name
:return:
"""
df = pd.DataFrame()
times = pd.date_range(start=start, periods=len(input_array), freq='T').strftime('%H:%M')
#Create a data frame for animation
for idx, time in enumerate(list(times)):
add_df = pd.DataFrame({x_label: [time for time in times [0:idx]],
y_label: input_array [0:idx],
'tick': idx})
df = pd.concat([df, add_df])
range_x_max = len(input_array) - 2
# plotly.Draw with express
if g_type == 'scatter':
fig = px.scatter(df,
x=x_label,
y=y_label,
animation_frame="tick",
range_y=[0, input_array.max()],
range_x=[0, range_x_max])
elif g_type == 'line':
fig = px.line(df,
x=x_label,
y=y_label,
animation_frame="tick",
range_y=[0, input_array.max()],
range_x=[0, range_x_max])
elif g_type == 'bar':
fig = px.bar(df,
x=x_label,
y=y_label,
animation_frame="tick",
range_y=[0, input_array.max()],
range_x=[0, range_x_max])
elif g_type == 'area':
fig = px.area(df,
x=x_label,
y=y_label,
animation_frame="tick",
range_y=[0, input_array.max()],
range_x=[0, range_x_max])
else:
raise KeyError('g_type is different')
return fig
```

```
input_array = np.array([_*np.random.rand() for _ in np.arange(0,30)*2])
create_animation_graph(input_array,g_type='area',start='00:00',x_label='Times of Day',y_label='Electric energy')
```

Recommended Posts