Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - Plotly icreate_animations offline on Jupyter Notebook

I am trying to replicate this plotly tutorial on a Jupyter Notebook with a dataset that matches the one given in the example, I just had to change the name of one column. The issue here is that being offline the command

py.icreate_animations(figure)

which in offline notebook mode becomes

icreate_animations(figure)

is not recognized. Furthermore, if I simply try the iplot(figure) command, which I use for static plots, a very long error is raised:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-27-b81a66612f63> in <module>()
     38 figure['layout']['sliders'] = [sliders_dict]
     39 
---> 40 iplot(figure)

//anaconda/lib/python2.7/site-packages/plotly/offline/offline.pyc in iplot(figure_or_data, show_link, link_text, validate, image, filename, image_width, image_height, config)
    330     config.setdefault('linkText', link_text)
    331 
--> 332     figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
    333 
    334     # Though it can add quite a bit to the display-bundle size, we include

//anaconda/lib/python2.7/site-packages/plotly/tools.pyc in return_figure_from_figure_or_data(figure_or_data, validate_figure)
   1383 
   1384         try:
-> 1385             graph_objs.Figure(figure)
   1386         except exceptions.PlotlyError as err:
   1387             raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
   1159 
   1160     def __init__(self, *args, **kwargs):
-> 1161         super(Figure, self).__init__(*args, **kwargs)
   1162         if 'data' not in self:
   1163             self.data = Data(_parent=self, _parent_key='data')

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
    375         d = {key: val for key, val in dict(*args, **kwargs).items()}
    376         for key, val in d.items():
--> 377             self.__setitem__(key, val, _raise=_raise)
    378 
    379     def __dir__(self):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __setitem__(self, key, value, _raise)
    430 
    431         if self._get_attribute_role(key) == 'object':
--> 432             value = self._value_to_graph_object(key, value, _raise=_raise)
    433             if not isinstance(value, (PlotlyDict, PlotlyList)):
    434                 return

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in _value_to_graph_object(self, key, value, _raise)
    541         # this can be `None` when `_raise == False`
    542         return GraphObjectFactory.create(key, value, _raise=_raise,
--> 543                                          _parent=self, _parent_key=key)
    544 
    545     def help(self, attribute=None, return_help=False):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in create(object_name, *args, **kwargs)
    791         class_name = graph_reference.OBJECT_NAME_TO_CLASS_NAME.get(object_name)
    792         if class_name in ['Figure', 'Data', 'Frames']:
--> 793             return globals()[class_name](*args, **kwargs)
    794         else:
    795             kwargs['_name'] = object_name

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
    156 
    157         for index, value in enumerate(list(*args)):
--> 158             value = self._value_to_graph_object(index, value, _raise=_raise)
    159 
    160             if isinstance(value, PlotlyBase):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in _value_to_graph_object(self, index, value, _raise)
   1291             return value
   1292         return super(Frames, self)._value_to_graph_object(index, value,
-> 1293                                                           _raise=_raise)
   1294 
   1295     def to_string(self, level=0, indent=4, eol='
',

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in _value_to_graph_object(self, index, value, _raise)
    221                 return GraphObjectFactory.create(item, _raise=_raise,
    222                                                  _parent=self,
--> 223                                                  _parent_key=index, **value)
    224             except exceptions.PlotlyGraphObjectError:
    225                 if i == len(items) and _raise:

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in create(object_name, *args, **kwargs)
    797                 return PlotlyList(*args, **kwargs)
    798             else:
--> 799                 return PlotlyDict(*args, **kwargs)
    800 
    801 

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
    375         d = {key: val for key, val in dict(*args, **kwargs).items()}
    376         for key, val in d.items():
--> 377             self.__setitem__(key, val, _raise=_raise)
    378 
    379     def __dir__(self):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __setitem__(self, key, value, _raise)
    430 
    431         if self._get_attribute_role(key) == 'object':
--> 432             value = self._value_to_graph_object(key, value, _raise=_raise)
    433             if not isinstance(value, (PlotlyDict, PlotlyList)):
    434                 return

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in _value_to_graph_object(self, key, value, _raise)
    541         # this can be `None` when `_raise == False`
    542         return GraphObjectFactory.create(key, value, _raise=_raise,
--> 543                                          _parent=self, _parent_key=key)
    544 
    545     def help(self, attribute=None, return_help=False):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in create(object_name, *args, **kwargs)
    791         class_name = graph_reference.OBJECT_NAME_TO_CLASS_NAME.get(object_name)
    792         if class_name in ['Figure', 'Data', 'Frames']:
--> 793             return globals()[class_name](*args, **kwargs)
    794         else:
    795             kwargs['_name'] = object_name

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
    156 
    157         for index, value in enumerate(list(*args)):
--> 158             value = self._value_to_graph_object(index, value, _raise=_raise)
    159 
    160             if isinstance(value, PlotlyBase):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in _value_to_graph_object(self, index, value, _raise)
   1059         return GraphObjectFactory.create(item, _raise=_raise,
   1060                                          _parent=self,
-> 1061                                          _parent_key=index, **value)
   1062 
   1063     def get_data(self, flatten=False):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in create(object_name, *args, **kwargs)
    797                 return PlotlyList(*args, **kwargs)
    798             else:
--> 799                 return PlotlyDict(*args, **kwargs)
    800 
    801 

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __init__(self, *args, **kwargs)
    375         d = {key: val for key, val in dict(*args, **kwargs).items()}
    376         for key, val in d.items():
--> 377             self.__setitem__(key, val, _raise=_raise)
    378 
    379     def __dir__(self):

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs.pyc in __setitem__(self, key, value, _raise)
    400         if key.endswith('src'):
    401             if key in self._get_valid_attributes():
--> 402                 value = graph_objs_tools.assign_id_to_src(key, value)
    403                 return super(PlotlyDict, self).__setitem__(key, value)
    404 

//anaconda/lib/python2.7/site-packages/plotly/graph_objs/graph_objs_tools.pyc in assign_id_to_src(src_name, src_value)
    254     if src_id == '':
    255         err = exceptions.COLUMN_NOT_YET_UPLOADED_MESSAGE
--> 256         err.format(column_name=src_value.name, reference=src_name)
    257         raise exceptions.InputError(err)
    258     return src_id

AttributeError: 'str' object has no attribute 'name'

So, does anyone know how to make that plot in offline mode?

EDIT: I upload the whole code:

import pandas as pd
import numpy as np
from __future__ import division
import plotly.plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()

from plotly.grid_objs import Grid, Column
from plotly.tools import FigureFactory as FF 

dataset=pd.read_csv('gdp_mod_copia.csv')

years_from_col = set(dataset['year'])
years_ints = sorted(list(years_from_col))
years = [str(year) for year in years_ints]


# make list of continents
continents = []
for continent in dataset['continent']:
    if continent not in continents: 
        continents.append(continent)

columns = []
# make grid
for year in years:
    for continent in continents:
        dataset_by_year = dataset[dataset['year'] == int(year)]
        dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent]
        for col_name in dataset_by_year_and_cont:
            # each column name is unique
            column_name = '{year}+{continent}+{header}_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)



figure = {
    'data': [],
    'layout': {},
    'frames': [],
    'config': {'scrollzoom': True}
}

# fill in most of layout
figure['layout']['xaxis'] = {'range': [30, 85], 'title': 'Life Expectancy', 'gridcolor': '#FFFFFF'}
figure['layout']['yaxis'] = {'title': 'GDP per Capita', 'type': 'log', 'gridcolor': '#FFFFFF'}
figure['layout']['hovermode'] = 'closest'
figure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)'
figure['layout']['slider'] = {
    'args': [
        'slider.value', {
            'duration': 400,
            'ease': 'cubic-in-out'
        }
    ],
    'initialValue': '2007',
    'plotlycommand': 'animate',
    'values': years,
    'visible': True
}

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'
    }
]
sliders_dict = {
    'active': 0,
    'yanchor': 'top',
    'xanchor': 'left',
    'currentvalue': {
        'font': {'size': 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So lets start with the issues in the code.

  1. You are using from plotly.grid_objs import Grid, Column to make the graph but this is a functionality of plotly online, I have substituted your logic for grid with a simple dataframe, which basically does the same thing.

  2. Second, I noticed that the graph was not displaying data, after analyzing I finally found out that you had set the range for X-Axis to [30, 85], but the X-Axis values between 1-15k.

Please find below my updated code. I hope this solves your issue.

Code:

import pandas as pd
import numpy as np
from __future__ import division
import plotly.plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()

from plotly.grid_objs import Grid, Column
from plotly.tools import FigureFactory as FF 

dataset=pd.read_csv('god_mod_copia.csv')

years_from_col = set(dataset['year'])
years_ints = sorted(list(years_from_col))
years = [str(year) for year in years_ints]
# make list of continents
continents = []
for continent in dataset['continent']:
    if continent not in continents: 
        continents.append(continent)
df = pd.DataFrame()
# make grid
for year in years:
    for continent in continents:
        dataset_by_year = dataset[dataset['year'] == int(year)]
        dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent]
        for col_name in dataset_by_year_and_cont:
            # each column name is unique
            temp = '{year}+{continent}+{header}_grid'.format(
                year=year, continent=continent, header=col_name
            )
            #if dataset_by_year_and_cont[col_name].size != 0:
            df = df.append({'value': list(dataset_by_year_and_cont[col_name]), 'key': temp}, ignore_index=True)

figure = {
    'data': [],
    'layout': {},
    'frames': []
}
figure['layout']['xaxis'] = {'title': 'GDP per Capita', 'type': 'log', 'autorange': True} #was not set properly
figure['layout']['yaxis'] = {'title': 'Life Expectancy', 'autorange': True} #was not set properly
figure['layout']['hovermode'] = 'closest'
figure['layout']['showlegend'] = True
figure['layout']['sliders'] = {
    'args': [
        'slider.value', {
            'duration': 400,
            'ease': 'cubic-in-out'
        }
    ],
    'initialValue': '2007',
    'plotlycommand': 'animate',
    'values': years,
    'visible': True
}
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'
    }
]

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': []
}



custom_colors = {
    'Asia': 'rgb(171, 99, 250)',
    'Europe': 'rgb(230, 99, 250)',
    'Africa': 'rgb(99, 110, 250)',
    'Americas': 'rgb(25, 211, 243)',
    #'Oceania': 'rgb(9, 255, 255)' 
    'Oceania': 'rgb(50, 170, 255)'
}

col_name_template = '{year}+{continent}+{header}_grid'
year = 2007
for continent in continents:
    data_dict = {
        'x': df.loc[df['key']==col_name_template.format(
            year=year, continent=continent, header='GDP_per_capita'
        ), 'value'].values[0],
        'y': df.loc[df['key']==col_name_template.format(
            year=year, continent=continent, header='Life_satisfaction'
        ), 'value'].values[0],
        'mode': 'markers',
        'text': df.loc[df['key']==col_name_template.format(
            year=year, continent=continent, header='country'
        ), 'value'].values[0],
        'marker': {
            'sizemode': 'area',
            'sizeref': 200000,
            'size': df.loc[df['key']==col_name_template.format(
                year=year, continent=continent, header='Total_population'
            ), 'value'].values[0],
            'color': custom_colors[continent]
        },
        'name': continent
    }
    figure['data'].append(data_dict)

for year in years:
    frame = {'data': [], 'name': str(year)}
    for continent in continents:
        data_dict = {
            'x': df.loc[df['key']==col_name_template.format(
                year=year, continent=continent, header='GDP_per_capita'
            ), 'value'].values[0],
            'y': df.loc[df['key']==col_name_template.format(
                year=year, continent=continent, header='Life_satisfaction'
            ), 'value'].values[0],
            'mode': 'markers',
            'text': df.loc[df['key']==col_name_template.format(
                year=year, continent=continent, header='country'
            ), 'value'].values[0],
            'marker': {
                'sizemode': 'area',
                'sizeref': 200000,
                'size': df.loc[df['key']==col_name_template.format(
                    year=year, continent=continent, header='Total_population'
                ), 'value'].values[0],
                'color': custom_colors[continent]
            },
            'name': continent
        }
        frame['data'].append(data_dict)

    figure['frames'].append(frame) #this block was indented and should not have been.
    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]
iplot(figure, config={'scrollzoom': True})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...