Карты с Python на Kaggle: карта не отображается - PullRequest
0 голосов
/ 28 августа 2018

ВОПРОС ОБНОВЛЕН - см. Раздел редактирования ниже!

Я работаю над набором данных Kaggle о недавней истории Олимпийских игр .

Я хотел бы добавить в ядро ​​несколько карт, чтобы отображать распределение золотого медалиста по всему миру, используя сюжет.

Я использовал следующий код, который не отображает вывод, не могли бы вы помочь?

import plotly.graph_objs as go 
from plotly.offline import init_notebook_mode,iplot
init_notebook_mode(connected=True)

data = dict(type = 'choropleth',
            locations = goldMedals['region'],
            locationmode = 'country names',
            colorscale = 'Viridis',
            reversescale = True,
            text= goldMedals['region'],
            z = goldMedals['region'],
            colorbar = {'title':'gold medals'})

layout = dict(title = 'gold medals',
                geo = dict(showframe = False,projection = {'type':'Mercator'})
             )

Если вам нужно просмотреть все данные, которые вы можете просмотреть полное ядро ​​на Kaggle .

РЕДАКТИРОВАТЬ 1 : Благодаря полученному первому ответу я добавил следующий код для отображения карты, но получаю значениеError

fig = dict(data=data, layout=layout)
iplot(fig)

ОШИБКА:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-62ab92846e12> in <module>()
      1 fig = dict(data=data, layout=layout)
----> 2 iplot(fig)

/opt/conda/lib/python3.6/site-packages/plotly/offline/offline.py in iplot(figure_or_data, show_link, link_text, validate, image, filename, image_width, image_height, config)
    334     config.setdefault('linkText', link_text)
    335 
--> 336     figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
    337 
    338     # Though it can add quite a bit to the display-bundle size, we include

/opt/conda/lib/python3.6/site-packages/plotly/tools.py in return_figure_from_figure_or_data(figure_or_data, validate_figure)
   1473 
   1474         try:
-> 1475             figure = Figure(**figure).to_dict()
   1476         except exceptions.PlotlyError as err:
   1477             raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "

/opt/conda/lib/python3.6/site-packages/plotly/graph_objs/_figure.py in __init__(self, data, layout, frames)
    312                         respective traces in the data attribute
    313         """
--> 314         super(Figure, self).__init__(data, layout, frames)
    315 
    316     def add_area(

/opt/conda/lib/python3.6/site-packages/plotly/basedatatypes.py in __init__(self, data, layout_plotly, frames)
    114 
    115         # ### Import traces ###
--> 116         data = self._data_validator.validate_coerce(data)
    117 
    118         # ### Save tuple of trace objects ###

/opt/conda/lib/python3.6/site-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v)
   1977 
   1978         else:
-> 1979             self.raise_invalid_val(v)
   1980 
   1981         return v

/opt/conda/lib/python3.6/site-packages/_plotly_utils/basevalidators.py in raise_invalid_val(self, v)
    214             typ=type_str(v),
    215             v=repr(v),
--> 216             valid_clr_desc=self.description()))
    217 
    218     def raise_invalid_elements(self, invalid_els):

ValueError: 
    Invalid value of type 'builtins.dict' received for the 'data' property of 
        Received value: {'type': 'choropleth', 'locations': 3             Denmark
42            Finland
44            Finland
48            Finland
60             Norway
73             Norway
76             Norway
78             Norway
79             Norway
113            Norway
117            Norway
150            France
172           Belarus
173            France
174            France
178          Cameroon
182             Spain
188             Spain
200            France
218             Italy
219             Italy
220             Italy
221             Italy
222             Italy
226             Italy
227             Italy
283               USA
524          Pakistan
550            Russia
587        Uzbekistan
             ...     
270411          Italy
270416          Italy
270431          China
270432          China
270433          China
270434          China
270435          China
270439          China
270440          China
270477         Serbia
270480         Russia
270514        Croatia
270552        Hungary
270588         Russia
270609         Russia
270610         Russia
270641         Russia
270676          Italy
270770        Germany
270773         Russia
270876    Switzerland
270896        Germany
270917    Switzerland
270934         Russia
270970        Belarus
270981        Georgia
271009        Germany
271016    Netherlands
271049    Netherlands
271076         Russia
Name: region, Length: 13224, dtype: object, 'locationmode': 'country names', 'colorscale': 'Viridis', 'reversescale': True, 'text': 3             Denmark
42            Finland
44            Finland
48            Finland
60             Norway
73             Norway
76             Norway
78             Norway
79             Norway
113            Norway
117            Norway
150            France
172           Belarus
173            France
174            France
178          Cameroon
182             Spain
188             Spain
200            France
218             Italy
219             Italy
220             Italy
221             Italy
222             Italy
226             Italy
227             Italy
283               USA
524          Pakistan
550            Russia
587        Uzbekistan
             ...     
270411          Italy
270416          Italy
270431          China
270432          China
270433          China
270434          China
270435          China
270439          China
270440          China
270477         Serbia
270480         Russia
270514        Croatia
270552        Hungary
270588         Russia
270609         Russia
270610         Russia
270641         Russia
270676          Italy
270770        Germany
270773         Russia
270876    Switzerland
270896        Germany
270917    Switzerland
270934         Russia
270970        Belarus
270981        Georgia
271009        Germany
271016    Netherlands
271049    Netherlands
271076         Russia
Name: region, Length: 13224, dtype: object, 'z': 3             Denmark
42            Finland
44            Finland
48            Finland
60             Norway
73             Norway
76             Norway
78             Norway
79             Norway
113            Norway
117            Norway
150            France
172           Belarus
173            France
174            France
178          Cameroon
182             Spain
188             Spain
200            France
218             Italy
219             Italy
220             Italy
221             Italy
222             Italy
226             Italy
227             Italy
283               USA
524          Pakistan
550            Russia
587        Uzbekistan
             ...     
270411          Italy
270416          Italy
270431          China
270432          China
270433          China
270434          China
270435          China
270439          China
270440          China
270477         Serbia
270480         Russia
270514        Croatia
270552        Hungary
270588         Russia
270609         Russia
270610         Russia
270641         Russia
270676          Italy
270770        Germany
270773         Russia
270876    Switzerland
270896        Germany
270917    Switzerland
270934         Russia
270970        Belarus
270981        Georgia
271009        Germany
271016    Netherlands
271049    Netherlands
271076         Russia
Name: region, Length: 13224, dtype: object, 'colorbar': {'title': 'gold medals'}}

    The 'data' property is a tuple of trace instances
    that may be specified as:
      - A list or tuple of trace instances
        (e.g. [Scatter(...), Bar(...)])
      - A list or tuple of dicts of string/value properties where:
        - The 'type' property specifies the trace type
            One of: ['area', 'bar', 'box', 'candlestick', 'carpet',
                     'choropleth', 'cone', 'contour',
                     'contourcarpet', 'heatmap', 'heatmapgl',
                     'histogram', 'histogram2d',
                     'histogram2dcontour', 'mesh3d', 'ohlc',
                     'parcoords', 'pie', 'pointcloud', 'sankey',
                     'scatter', 'scatter3d', 'scattercarpet',
                     'scattergeo', 'scattergl', 'scattermapbox',
                     'scatterpolar', 'scatterpolargl',
                     'scatterternary', 'splom', 'streamtube',
                     'surface', 'table', 'violin']

        - All remaining properties are passed to the constructor of
          the specified trace type

        (e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}])

1 Ответ

0 голосов
/ 29 августа 2018

Чтобы создать вывод, вам нужно создать фигуру с переменными data и layout. Затем используйте iplot для отображения цифры.

fig = dict(data=data, layout=layout)
iplot(fig)

В зависимости от типа карты, которую вы пытаетесь создать, вам может потребоваться переформатировать переменные data и layout. Вы можете найти различные варианты карты здесь .

...