def make_the_figure(self): def to_unix_time(self, dtime): epoch = dt.datetime.utcfromtimestamp(0) return (dtime - epoch).total_seconds() * 1000 grid = self.make_the_grid() data = [dict(type='scatter', xsrc=grid.get_column_reference('x1'), ysrc=grid.get_column_reference('y1'), name='close', mode='lines', line=dict(color='rgb(114, 186, 59)'), fill='tozeroy', fillcolor='rgba(114, 186, 59, 0.5)')] axis = dict(ticklen=4, mirror=True, zeroline=False, showline=True, autorange=False, showgrid=False) layout = dict(title='002237', font=dict(family='Balto'), showlegend=False, autosize=False, width=800, height=400, xaxis=dict(axis, **{'nticks': 12, 'tickangle': -45, 'range': [to_unix_time(self, dt.datetime(2010, 1, 1)), to_unix_time(self, dt.datetime(2017, 1, 1))]}), yaxis=dict(axis, **{'title': '$', 'range': [0, 120]}), updatemenus=[dict(type='buttons', showactive=False, y=1, x=1.1, xanchor='right', yanchor='top', pad=dict(t=0, r=10), buttons=[dict(label='Play', method='animate', args=[None, dict(frame=dict(duration=50, redraw=False), transition=dict( duration=0), fromcurrent=True, mode='immediate')])])]) frames = [{'data': [{'xsrc': grid.get_column_reference('x{}'.format(i - 1)), 'ysrc': grid.get_column_reference('y{}'.format(i - 1))}], 'traces': [0] } for i in range(1, self.n)] fig = dict(data=data, layout=layout, frames=frames) py.icreate_animations(fig, 'AAPL-stockprice' + str(time.time()))
), ) # In[]: # Create frames frames = [] for i, year in enumerate(years): # Create frame for each subplot frame_trace1 = dict( locationssrc=grid.get_column_reference("location{}".format(i + 1)), zsrc=grid.get_column_reference("z{}".format(i + 1)), ) frame = dict( data=[frame_trace1], name=year, traces=[0], ) frames.append(frame) # In[]: # Upload animation data = [trace1] figure = dict(data=data, layout=layout, frames=frames) py.icreate_animations(figure, filename=chart_filename, auto_open=False)
def animated_chart(merged_df): ''' Gera um plot animado. O eixo x merged_df.columns[3], sendo o eixo y merged_df.columns[2], a legenda sendo os continentes, o tamanho dos circulos sendo merged_df.columns[4] e o controle deslizante é a variação dos anos de 1975 a 2014. Parameters: ----------- merged_df -> dataframe de 5 colunas, a configuração do gráfico exige formatação correta da coluna: eixo x merged_df.columns[3], sendo o eixo y merged_df.columns[2], A legenda sendo os continentes, O tamanho dos circulos sendo merged_df.columns[4] O controle deslizante é a variação dos anos de 1975 a 2014. Return: ------- Um gráfico animado. Example: -------- animated_chart(merged_df) ''' #Normalizando os dados para impedir problemas de escala: norm = lambda df: preprocessing.MinMaxScaler().fit_transform( np.array(df, dtype="float64").reshape(-1, 1)) for i in merged_df.columns[2:-1]: merged_df[i] = norm(merged_df[i]) #Criando lista de anos e continentes para usar na legenda e controle deslizante: List_of_years = list(range(1975, 2015)) List_Of_Continents = list(set(Continents.values())) merged_df['Year'] = merged_df['Year'].apply(int) columns = [] # Fazendo o grid: for year in List_of_years: for continent in List_Of_Continents: dataset_by_year = merged_df[merged_df['Year'] == int(year)] dataset_by_year_and_cont = dataset_by_year[ dataset_by_year['Continents'] == continent] for col_name in dataset_by_year_and_cont: column_name = '{year}_{continent}_{header}_gapminder_grid'.format( year=year, continent=continent, header=col_name) a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name) columns.append(a_column) grid = Grid(columns) url = py.grid_ops.upload(grid, 'GDP.rateplot' + str(time.time()), auto_open=False) url #Criando a figura: figure1 = { 'data': [], 'layout': {}, 'frames': [], 'config': { 'scrollzoom': True } } figure1['layout']['xaxis'] = { 'title': list(merged_df.columns)[3], 'gridcolor': '#FFFFFF' } figure1['layout']['yaxis'] = { 'title': list(merged_df.columns)[2], 'type': 'log', 'gridcolor': '#FFFFFF' } figure1['layout']['hovermode'] = 'closest' figure1['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)' #Criando Controle Deslizante: sliders_dict = { 'active': 0, 'yanchor': 'top', 'xanchor': 'left', 'currentvalue': { 'font': { 'size': 20 }, 'prefix': 'Year:', 'visible': True, 'xanchor': 'right' }, 'transition': { 'duration': 300, 'easing': 'cubic-in-out' }, 'pad': { 'b': 10, 't': 50 }, 'len': 0.9, 'x': 0.1, 'y': 0, 'steps': [] } #Criando legendas: figure1['layout']['updatemenus'] = [{ 'buttons': [{ 'args': [ None, { 'frame': { 'duration': 500, 'redraw': False }, 'fromcurrent': True, 'transition': { 'duration': 300, 'easing': 'quadratic-in-out' } } ], 'label': 'Play', 'method': 'animate' }, { 'args': [[None], { 'frame': { 'duration': 0, 'redraw': False }, 'mode': 'immediate', 'transition': { 'duration': 0 } }], 'label': 'Pause', 'method': 'animate' }], 'direction': 'left', 'pad': { 'r': 10, 't': 87 }, 'showactive': False, 'type': 'buttons', 'x': 0.1, 'xanchor': 'right', 'y': 0, 'yanchor': 'top' }] custom_colors = { 'East Asia & Pacific': 'rgb(171, 99, 250)', 'Europe & Central Asia': 'rgb(230, 99, 250)', 'Africa': 'rgb(99, 110, 250)', 'Latin America & Caribbean': 'rgb(25, 211, 243)', 'Middle East & North Africa': 'rgb(50, 170, 255)', 'North America': 'rgb(215,20,20)', 'South Asia': 'rgb(20,215,20)', 'Sub-Saharan Africa': 'rgb(0,0,0)', } #Criando layout da figura: col_name_template = '{year}_{continent}_{header}_gapminder_grid' year = 1975 for continent in List_Of_Continents: data_dict = { 'xsrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list(merged_df.columns)[3])), 'ysrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list(merged_df.columns)[2])), 'mode': 'markers', 'textsrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header='Country')), 'marker': { 'sizemode': 'area', 'sizeref': 0.005, 'sizesrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list( merged_df.columns)[4])), 'color': custom_colors[continent] }, 'name': continent } figure1['data'].append(data_dict) for year in List_of_years: frame = {'data': [], 'name': str(year)} for continent in List_Of_Continents: data_dict = { 'xsrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list( merged_df.columns)[3])), 'ysrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list( merged_df.columns)[2])), 'mode': 'markers', 'textsrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header='Country')), 'marker': { 'sizemode': 'area', 'sizeref': 0.005, 'sizesrc': grid.get_column_reference( col_name_template.format(year=year, continent=continent, header=list( merged_df.columns)[4])), 'color': custom_colors[continent] }, 'name': continent } frame['data'].append(data_dict) figure1['frames'].append(frame) slider_step = { 'args': [[year], { 'frame': { 'duration': 300, 'redraw': False }, 'mode': 'immediate', 'transition': { 'duration': 300 } }], 'label': year, 'method': 'animate' } sliders_dict['steps'].append(slider_step) figure1['layout']['sliders'] = [sliders_dict] #Plotando: return py.icreate_animations(figure1, 'Plot1CreditGDP' + str(time.time()))
width=600, height=600, scene=dict(xaxis=(axis3d), yaxis=(axis3d), zaxis=dict(axis3d, **dict(range=[-0.1, 6.8], autorange=False)), aspectratio=dict(x=1, y=1, z=1), ), updatemenus=[ dict(type='buttons', showactive=False, y=1, x=1.3, xanchor='right', yanchor='top', pad=dict(t=0, r=10), buttons=[dict(label='Play', method='animate', args=[ None, dict(frame=dict(duration=70, redraw=False), transition=dict(duration=0), fromcurrent=True, mode='immediate') ])]) ], sliders=sliders ) fig=dict(data=data, layout=layout3d, frames=frames) py.icreate_animations(fig, filename='animslicesHead'+str(time.time()))
pad=dict(t=0, r=10), buttons=[ dict(label='Play', method='animate', args=[ None, dict(frame=dict(duration=1000, redraw=True), transition=dict(duration=0), fromcurrent=True, mode='immediate') ]) ]) ]) frames = [ dict( data=[ dict( zsrc=grid.get_column_reference( 'z{}'.format(k)), #add the others here zmax=-20) ], traces=[0], name='frame{}'.format(k), ) for k in range(2, 38) ] fig = dict(data=data, layout=layout, frames=frames) py.icreate_animations(fig, filename='animheatmap' + str(time.time()))
'mode': 'markers', 'textsrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='country' )), 'marker': { 'sizemode': 'area', 'sizeref': 200000, 'sizesrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='pop' )), 'color': custom_colors[continent] }, 'name': continent } frame['data'].append(data_dict) figure['frames'].append(frame) slider_step = {'args': [ [year], {'frame': {'duration': 300, 'redraw': False}, 'mode': 'immediate', 'transition': {'duration': 300}} ], 'label': year, 'method': 'animate'} sliders_dict['steps'].append(slider_step) figure['layout']['sliders'] = [sliders_dict] py.icreate_animations(figure, 'gapminder_example'+str(time.time()))
}, 'name': province } frame['data'].append(data_dict) figure['frames'].append(frame) slider_step = { 'args': [[year], { 'frame': { 'duration': 300, 'redraw': False }, 'mode': 'immediate', 'transition': { 'duration': 300 } }], 'label': year, 'method': 'animate' } sliders_dict['steps'].append(slider_step) figure['layout']['sliders'] = [sliders_dict] graph = py.icreate_animations(figure, 'SLA_fatalities_turnout' + str(time.time())) graph
'ysrc': grid.get_column_reference('y3'), 'mode': 'markers', 'marker': { 'color': '#26828e', 'size': 50 } }] }, { 'data': [{ 'xsrc': grid.get_column_reference('x4'), 'ysrc': grid.get_column_reference('y4'), 'mode': 'markers', 'marker': { 'color': '#5ec962', 'size': 80 } }] }, { 'data': [{ 'xsrc': grid.get_column_reference('x5'), 'ysrc': grid.get_column_reference('y5'), 'mode': 'markers', 'marker': { 'color': '#d8e219', 'size': 100 } }] }] } py.icreate_animations(figure, 'points_changing_size' + str(time.time()))
'args': [None], 'label': 'Play', 'method': 'animate' }], 'pad': { 'r': 10, 't': 87 }, 'showactive': False, 'type': 'buttons' }] }, 'frames': [{ 'data': [{ 'xsrc': grid.get_column_reference('x2'), 'ysrc': grid.get_column_reference('y2'), 'mode': 'markers', }] }, { 'data': [{ 'xsrc': grid.get_column_reference('x'), 'ysrc': grid.get_column_reference('y'), 'mode': 'markers', }] }] } py.icreate_animations(figure, 'ping_pong' + str(time.time()))
def visualization_Q4(dataframe): """ Make visualization for question 4 Input: dataframe Output: plotly image """ df_0 = dataframe years_from_col = set(df_0['year']) years_ints = sorted(list(years_from_col)) years = [str(year) for year in years_ints] # make list of continents continents = [] for continent in df_0['region']: if continent not in continents: continents.append(continent) columns = [] # make grid for year in years: for continent in continents: dataset_by_year = df_0[df_0['year'] == year] dataset_by_year_and_cont = dataset_by_year[dataset_by_year['region'] == continent] for col_name in dataset_by_year_and_cont: # each column name is unique column_name = '{year}_{continent}_{header}_gapminder_grid'.format( year=year, continent=continent, header=col_name ) a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name) columns.append(a_column) # upload grid grid = Grid(columns) url = py.grid_ops.upload(grid, 'gapminder_grid'+str(time.time()), auto_open=False) figure = { 'data': [], 'layout': {}, 'frames': [], 'config': {'scrollzoom': True} } # fill in most of layout figure['layout']['xaxis'] = {'title': 'Number of events per month by country', 'gridcolor': '#FFFFFF'} figure['layout']['yaxis'] = {'title': 'Emotion charge', 'range':[0,0.25], 'gridcolor': '#FFFFFF'} figure['layout']['hovermode'] = 'closest' figure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)' figure['layout']['sliders'] = { 'active': 0, 'yanchor': 'top', 'xanchor': 'left', 'currentvalue': { 'font': {'size': 20}, 'prefix': 'text-before-value-on-display', 'visible': True, 'xanchor': 'right' }, 'transition': {'duration': 300, 'easing': 'cubic-in-out'}, 'pad': {'b': 10, 't': 50}, 'len': 0.9, 'x': 0.1, 'y': 0, 'steps': [...] } { 'method': 'animate', 'label': 'label-for-frame', 'value': 'value-for-frame(defaults to label)', 'args': [{'frame': {'duration': 300, 'redraw': False}, 'mode': 'immediate'} ], } sliders_dict = { 'active': 0, 'yanchor': 'top', 'xanchor': 'left', 'currentvalue': { 'font': {'size': 20}, 'prefix': 'Year:', 'visible': True, 'xanchor': 'right' }, 'transition': {'duration': 300, 'easing': 'cubic-in-out'}, 'pad': {'b': 10, 't': 50}, 'len': 0.9, 'x': 0.1, 'y': 0, 'steps': [] } figure['layout']['updatemenus'] = [ { 'buttons': [ { 'args': [None, {'frame': {'duration': 500, 'redraw': False}, 'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}], 'label': 'Play', 'method': 'animate' }, { 'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate', 'transition': {'duration': 0}}], 'label': 'Pause', 'method': 'animate' } ], 'direction': 'left', 'pad': {'r': 10, 't': 87}, 'showactive': False, 'type': 'buttons', 'x': 0.1, 'xanchor': 'right', 'y': 0, 'yanchor': 'top' } ] col_name_template = '{year}_{continent}_{header}_gapminder_grid' year = '2015_02' for continent in continents: data_dict = { 'xsrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='CountCountrySource' )), 'ysrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='NormEvnt' )), 'mode': 'markers', 'textsrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='CountrySource' )), 'marker': { 'sizemode': 'area', 'sizeref': 200000, 'sizesrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='SizeToViz' )) }, 'name': continent } figure['data'].append(data_dict) for year in years: frame = {'data': [], 'name': str(year)} for continent in continents: data_dict = { 'xsrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='CountCountrySource' )), 'ysrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='NormEvnt' )), 'mode': 'markers', 'textsrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='CountrySource' )), 'marker': { 'sizemode': 'area', 'sizeref': 200000, 'sizesrc': grid.get_column_reference(col_name_template.format( year=year, continent=continent, header='SizeToViz' )) }, 'name': continent } frame['data'].append(data_dict) figure['frames'].append(frame) slider_step = {'args': [ [year], {'frame': {'duration': 300, 'redraw': False}, 'mode': 'immediate', 'transition': {'duration': 300}} ], 'label': year, 'method': 'animate'} sliders_dict['steps'].append(slider_step) figure['layout']['sliders'] = [sliders_dict] py.icreate_animations(figure)