{"cells":[{"metadata":{"_uuid":"39dffff470fd0dfae7ab1790ba8e9152f5b44894"},"cell_type":"markdown","source":"<h1><center>PLOTLY TUTORIAL - 4</center></h1>\n\n***\n\nIn this notebook, my aim is to investigate Google Merchandise Store customer dataset by using plotly time-series features and custom buttons while generating a comprehensive tutorial for plotly enthusiasts. You may want to check my other Plotly tutorials.\n\n**PLOTLY TUTORIAL - 1 (Kaggle Survey 2017): https://www.kaggle.com/hakkisimsek/plotly-tutorial-1**\n\n**PLOTLY TUTORIAL - 2 (2015 Flight Delays and Cancellations): https://www.kaggle.com/hakkisimsek/plotly-tutorial-2**\n\n**PLOTLY TUTORIAL - 3 (S&P 500 Stock Data): https://www.kaggle.com/hakkisimsek/plotly-tutorial-3**\n\n**PLOTLY TUTORIAL - 5 (Kaggle Survey 2018): https://www.kaggle.com/hakkisimsek/plotly-tutorial-5**"},{"metadata":{"trusted":true,"_uuid":"1761a65e8ca35e1c1a8fb965b87849529e5bda4a","_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\ncolor = sns.color_palette()\n\nimport os\nimport datetime\n\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nprint(os.listdir(\"../input\"))\ndf = pd.read_csv('../input/train-set/extracted_train/extracted_train', \n                    dtype={'date': str, 'fullVisitorId': str, 'sessionId':str},\n                    nrows=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"612936f4c148ad907781f2192ae0ba8fae1e504f"},"cell_type":"markdown","source":"**Before starting the explanatory data analysis, we should change type of transaction revenue to float and create date-related features.**"},{"metadata":{"trusted":true,"_uuid":"f6f432ee26269a5a2ba2da781f66f38f4a0a590e","_kg_hide-input":true},"cell_type":"code","source":"df[\"totals.transactionRevenue\"] = df[\"totals.transactionRevenue\"].astype('float')\ndf['date'] = df['date'].apply(lambda x: datetime.date(int(str(x)[:4]), \n                                    int(str(x)[4:6]), int(str(x)[6:])))\ndf['time'] = pd.to_datetime(df['visitStartTime'], unit='s')\ndf['month'] = df['time'].dt.month\ndf['dow'] = df['time'].dt.dayofweek\ndf['day'] = df['time'].dt.day\ndf['hour'] = df['time'].dt.hour\n\ndf['day_frame'] = 0\ndf['day_frame'] = np.where((df[\"hour\"]>=0) & (df[\"hour\"]<4), 'overnight', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=4) & (df[\"hour\"]<8), 'dawn', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=8) & (df[\"hour\"]<12), 'morning', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=12) & (df[\"hour\"]<14), 'lunch', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=14) & (df[\"hour\"]<18), 'afternoon', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=18) & (df[\"hour\"]<21), 'evening', \n                           df['day_frame'])\ndf['day_frame'] = np.where((df[\"hour\"]>=21) & (df[\"hour\"]<24), 'night', \n                           df['day_frame'])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"59154edb486b939b0e7700d600d7ecfc115de682"},"cell_type":"markdown","source":"### Check missing values"},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"39e4220b22a3eceef2c70edb32cb9c827b55f208"},"cell_type":"code","source":"miss = pd.concat([df.isnull().sum(), 100 * df.isnull().sum()/len(df)], \n              axis=1).rename(columns={0:'Missing Records', \n                        1:'Percentage (%)'}).sort_values(by='Percentage (%)',\n                                                         ascending=False)[:8]\ntrace = go.Bar(\n        y=miss.index[::-1],\n        x=miss['Percentage (%)'][::-1],\n        showlegend=False,\n        orientation = 'h',\n        marker=dict(\n            color='firebrick',\n        )\n    )\n\ndata = [trace]\nlayout = dict(\n    title = 'Percentage (%) missing values',\n    margin  = dict(l = 200\n                                      )\n    )\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"edbcd9efda58793bb08d3979099661473ffd9ae7"},"cell_type":"markdown","source":"**As a starting point, it would be good to understand behavior of the target variable revenue transaction. Then, comparing behavior of total visitors, non-zero revenue visitors and total revenue  will be more meaningful.**"},{"metadata":{"trusted":true,"_uuid":"9c3ffdd5b5a90fd7208869747eaeebed0dacecfb","scrolled":true,"_kg_hide-input":true},"cell_type":"code","source":"def scatter_plot(data, color, name, mode=None):\n    trace = go.Scatter(\n        x=data.index[::-1],\n        y=data.values[::-1],\n        showlegend=False,\n        name = name,\n        mode = mode,\n        marker=dict(\n        color = color\n        )\n    )\n    return trace","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cd1d0bbd0b7dd0075ba5a050f5c8d7b92e7f6509"},"cell_type":"markdown","source":"**On the left graph, we show transaction revenues by visitors while on the right we calculate log of transaction revenues. It can be seen easily that most visitors do not have an effect on revenue. **\n\n**By following section, our aim is to understand which features are critical for seperating non-zero revenue visitors from others.**"},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"15dd890da52b94ac25c1a733a391ed6094b0d6d3"},"cell_type":"code","source":"f, ax = plt.subplots(1,2, figsize=(18,5))\nrev = df.groupby(\"fullVisitorId\")[\"totals.transactionRevenue\"].sum().reset_index()\n\nax[0].scatter(range(rev.shape[0]), \n              np.sort(rev[\"totals.transactionRevenue\"].values), color='navy')\nax[0].set_xlabel('index')\nax[0].set_ylabel('Revenue')\nax[0].set_title('Transaction revenue by visitors')\n\nax[1].scatter(range(rev.shape[0]), \n              np.sort(np.log1p(rev[\"totals.transactionRevenue\"].values)), \n              color='navy')\nax[1].set_xlabel('index')\nax[1].set_ylabel('Revenue (log)')\nax[1].set_title('Transaction revenue (log) by visitors')\nplt.show()\n\nvisit_group = df.groupby('fullVisitorId')['fullVisitorId'].count()\n\nfor i in [2, 10, 30, 50]:\n    print('Visitors that appear less than {} times: {}%'.format(i, \n                                 round((visit_group < i).mean() * 100, 2)))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"fe97c7f803ef91332af09c0b2dffb11367a7d11b"},"cell_type":"markdown","source":"**There are only 9996 non-zero revenue visitors out of 714167 visitors (1.3%). Let's analyze contributions of non-zero revenue visitors.**"},{"metadata":{"trusted":true,"scrolled":false,"_uuid":"df5891ecc553d53d939d9291c059f4155652fdb2","_kg_hide-input":true},"cell_type":"code","source":"rev = df.groupby(\"fullVisitorId\")[\"totals.transactionRevenue\"].sum().reset_index()\nrev1 = np.sort(rev[\"totals.transactionRevenue\"].values)\nrev2 = rev1[rev1>0]\nrev3 = np.sort(np.log1p(rev[\"totals.transactionRevenue\"].values))\nrev4 = rev3[rev3>0]\n\ntrace0 = scatter_plot(pd.DataFrame(rev2)[0],'red','revenue', mode='markers')\ntrace1 = scatter_plot(pd.DataFrame(rev4)[0],'red','revenue', mode='markers')\n\nfig = tools.make_subplots(rows=1, cols=2, \n                          subplot_titles=('Total revenue by user level',\n                                          'Total revenue (log) by user level'\n                                         )\n                         )\n\nfig.append_trace(trace0, 1, 1)\nfig.append_trace(trace1, 1, 2)\n\nfig['layout'].update(showlegend=False)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7e29106921fb4b641cae02341bbc530fd5812463"},"cell_type":"markdown","source":"**Now, we could apply groupby function on date and resample based on weekly and monthly basis. **"},{"metadata":{"trusted":true,"_uuid":"45e8b000c42c2ac1db51ab2b675b2bc1b78bf6a4","_kg_hide-input":true},"cell_type":"code","source":"stats = df.groupby('date')['totals.transactionRevenue'].agg(['size', 'count'])\nstats.columns = [\"count total\", \"count non-zero\"]\nstats.index = pd.to_datetime(stats.index)\nstats['per'] = stats['count non-zero'] / stats['count total']\n\ndf1dm = stats.reset_index().resample('D', on='date').mean()\ndf1wm = stats.reset_index().resample('W', on='date').mean()\ndf1mm = stats.reset_index().resample('M', on='date').mean()\n\ntrace0 = scatter_plot(df1mm['count total'].round(0), 'red', 'count')\ntrace1 = scatter_plot(df1wm['count total'].round(0), 'orange', 'count')\ntrace2 = scatter_plot(df1dm['count total'], 'indigo', 'count')\n\ntrace3 = scatter_plot(df1mm['count non-zero'].round(0), 'red', 'count')\ntrace4 = scatter_plot(df1wm['count non-zero'].round(0), 'orange', 'count')\ntrace5 = scatter_plot(df1dm['count non-zero'], 'indigo', 'count')\n\nfig = tools.make_subplots(rows=2, cols=3, \n                          subplot_titles=('Monthly total','Weekly', 'Daily',\n                                          'Monthly non-zero','Weekly', 'Daily'\n                                         )\n                         )\n\nfig.append_trace(trace0, 1, 1)\nfig.append_trace(trace1, 1, 2)\nfig.append_trace(trace2, 1, 3)\nfig.append_trace(trace3, 2, 1)\nfig.append_trace(trace4, 2, 2)\nfig.append_trace(trace5, 2, 3)\n\nfig['layout'].update(showlegend=False, \n                     title='Total visitors vs non-zero revenue visitors')\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"23489fe78eab0b0e95191dda64ba770561acfcd3"},"cell_type":"markdown","source":"**It is very interesting that trends in total visitors and non-zero revenue visitors do not overlap. Let's make analysis of non-zero visitors/total visitors.**"},{"metadata":{"trusted":true,"_uuid":"144862bb06ee2f601867446c40c4e364fbfbf215","_kg_hide-input":true},"cell_type":"code","source":"trace0 = scatter_plot(df1mm['per'].round(4), 'red', 'count', 'markers')\ntrace1 = scatter_plot(df1wm['per'].round(4), 'orange', 'count', 'markers')\ntrace2 = scatter_plot(df1dm['per'].round(4), 'indigo', 'count', 'markers')\n\nfig = tools.make_subplots(rows=2, cols=2, specs=[[{}, {}], \n                          [{'colspan': 2}, None]],\n                          subplot_titles=('Monthly','Weekly', 'Daily'\n                                         )\n                         )\nfig.append_trace(trace0, 1, 1)\nfig.append_trace(trace1, 1, 2)\nfig.append_trace(trace2, 2, 1)\n\nfig['layout'].update(showlegend=False, title='Non-zero/Total visitors')\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"178790dc09c99b8a6f79b7a6e61340c0de864500"},"cell_type":"markdown","source":"**Rather than creating graphs seperately as above, we could create custom buttons and make our work more interactive.**"},{"metadata":{"trusted":true,"_uuid":"bf2e67aefb4b5825f6235330e941c118e5d077df","_kg_hide-input":true},"cell_type":"code","source":"trace = go.Scatter(\n                   x=list(df1dm.index),\n                   y=list(df1dm.per.round(4)), \n                   line=dict(color='red'))\n\ndata = [trace]\nlayout = dict(\n    title='Non-zero/Total visitors',\n    xaxis=dict(\n        rangeselector=dict(\n            buttons=list([\n                dict(count=7,\n                     label='7d',\n                     step='day',\n                     stepmode='backward'),\n                dict(count=1,\n                     label='1m',\n                     step='month',\n                     stepmode='backward'),\n                dict(count=3,\n                     label='3m',\n                     step='month',\n                     stepmode='backward'),\n                dict(count=6,\n                     label='6m',\n                     step='month',\n                     stepmode='backward'),\n                dict(count=1,\n                    label='YTD',\n                    step='year',\n                    stepmode='todate')\n            ])\n        ),\n        rangeslider=dict(\n            visible = True\n        ),\n        type='date'\n    )\n)\n\nfig = dict(data=data, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5e1e87e8025488cd7e857ffbed937a9f073517d8"},"cell_type":"markdown","source":"**Using custom buttons, we could compare total visits, non-zero revenue visits and zero revenue visits across hours on a single graph easily.**"},{"metadata":{"trusted":true,"_uuid":"85afd3fae3a51087c99fb1f1f60b1d4be01d31d8","_kg_hide-input":true},"cell_type":"code","source":"trace = [\n    go.Histogram(x=df['hour'],\n                opacity = 0.7,\n                 name=\"Total Visits\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='grey')\n                ),\n    \n    go.Histogram(x=df[df['totals.transactionRevenue'].notnull()]['hour'],\n                 visible=False,\n                 opacity = 0.7,\n                 name = \"Non-zero revenue visits\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='red')\n                ),\n    \n    go.Histogram(x=df[df['totals.transactionRevenue'].isnull()]['hour'],\n                 visible=False,\n                opacity = 0.7,\n                 name = \"Zero revenue visits\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='aqua')         \n                )\n]\n\nlayout = go.Layout(title='Visiting hours',\n    paper_bgcolor = 'rgb(240, 240, 240)',\n     plot_bgcolor = 'rgb(240, 240, 240)',\n    autosize=True, xaxis=dict(tickmode=\"linear\"),\n                   yaxis=dict(title=\"# of Visits\",\n                             titlefont=dict(size=17)),\n                  )\n\nupdatemenus = list([\n    dict(\n    buttons=list([\n        dict(\n            args = [{'visible': [True, False, False]}],\n            label=\"Total visits\",\n            method='update',\n        ),\n        dict(\n            args = [{'visible': [False, True, False]}],\n            label=\"Non-zero revenue visits\",\n            method='update',\n        ),\n        dict(\n            args = [{'visible': [False, False, True]}],\n            label=\"Zero revenue visits\",\n            method='update',\n        ),\n        \n    ]),\n        direction=\"down\",\n        pad = {'r':10, \"t\":10},\n        x=0.1,\n        y=1.25,\n        yanchor='top',\n    )\n])\nlayout['updatemenus'] = updatemenus\n\nfig = dict(data=trace, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c8f7bdc34557ce52a1c23e94a556a10a17a46b08"},"cell_type":"markdown","source":"**We can say that it would be good to focus on graphs related to non-zero revenue visits rather than the hype.**\n\n**Now, we try to understand the relation between usage of operating system and revenue on different day frames. For doing such a task, a heatmap is a very good choice.**"},{"metadata":{"trusted":true,"_uuid":"f1bcef54d8212446fe09f92b0021afd305d27170","_kg_hide-input":true},"cell_type":"code","source":"fv = df.pivot_table(index=\"device.operatingSystem\",columns=\"day_frame\",\n                    values=\"totals.transactionRevenue\",aggfunc=lambda x:x.sum())\nfv = fv[['morning', 'lunch', 'afternoon', 'evening','night','overnight', 'dawn']]\nfv = fv.sort_values(by='morning', ascending=False)[:6]\n\ntrace = go.Heatmap(z=[fv.values[0],fv.values[1],fv.values[2],fv.values[3],\n                      fv.values[4],fv.values[5]],\n                   x=['morning', 'lunch', 'afternoon', 'evening', 'night',\n                      'overnight','dawn'],\n                   y=fv.index.values, colorscale='Blues', reversescale = True\n                  )\n\ndata=[trace]\nlayout = go.Layout(\n    title='Total Revenue by Device OS<br>(parts of the day)')\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"72eb969fd852a05e0085e4b9ded22cb2bee33302"},"cell_type":"markdown","source":"**Now, we can compare general statistics of operating systems like total count, non-zero revenue count and total revenue. Bar charts are common way to do such a task but I prefer to use pie chart now. **"},{"metadata":{"trusted":true,"_uuid":"d74fe93e5043cd77678787d1bfdc6e0d5b0f5061","_kg_hide-input":true},"cell_type":"code","source":"color = ['tomato',  'bisque','lightgreen', 'gold', 'tan', 'lightgrey', 'cyan']\n\ndef PieChart(column, title, limit):\n    revenue = \"totals.transactionRevenue\"\n    count_trace = df.groupby(column)[revenue].size().nlargest(limit).reset_index()\n    non_zero_trace = df.groupby(column)[revenue].count().nlargest(limit).reset_index()\n    rev_trace = df.groupby(column)[revenue].sum().nlargest(limit).reset_index()    \n\n    trace1 = go.Pie(labels=count_trace[column], \n                    values=count_trace[revenue], \n                    name= \"Visit\", \n                    hole= .5, textfont=dict(size=10),\n                    domain= {'x': [0, .32]},\n                   marker=dict(colors=color))\n\n    trace2 = go.Pie(labels=non_zero_trace[column], \n                    values=non_zero_trace[revenue], \n                    name=\"Revenue\", \n                    hole= .5,  textfont=dict(size=10),\n                    domain= {'x': [.34, .66]})\n    \n    trace3 = go.Pie(labels=rev_trace[column], \n                    values=rev_trace[revenue], \n                    name=\"Revenue\", \n                    hole= .5,  textfont=dict(size=10),\n                    domain= {'x': [.68, 1]})\n\n    layout = dict(title= title, font=dict(size=15), legend=dict(orientation=\"h\"),\n                  annotations = [\n                      dict(\n                          x=.10, y=.5,\n                          text='<b>Number of<br>Visitors', \n                          showarrow=False,\n                          font=dict(size=12)\n                      ),\n                      dict(\n                          x=.50, y=.5,\n                          text='<b>Number of<br>Visitors<br>(non-zero)', \n                          showarrow=False,\n                          font=dict(size=12)\n                      ),\n                      dict(\n                          x=.88, y=.5,\n                          text='<b>Total<br>Revenue', \n                          showarrow=False,\n                          font=dict(size=12)\n                      )\n        ])\n    \n    fig = dict(data=[trace1, trace2,trace3], layout=layout)\n    py.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"91078cf89088c8d12ad7c4ef6b44485f85a1ad06","_kg_hide-input":true},"cell_type":"code","source":"PieChart(\"device.operatingSystem\", \"Operating System\", 4)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6a53da584510d51826307ebaf75dd5ffd742c814"},"cell_type":"markdown","source":"**Although Windows users create a lot of traffic at the end of the day Macintosh users create non-zero revenue traffic and total revenue.**\n\n**Let's apply same steps on traffic source in terms of day of week. We analyze which sources give us more traffic, number of non-zero revenue traffic and total revenue. By doing so, we understand the real effect of a source on revenues.  **"},{"metadata":{"trusted":true,"_uuid":"982cdc00d79ecb332d1aae28fd33339aedf76a10","_kg_hide-input":true},"cell_type":"code","source":"fv = df.pivot_table(index=\"trafficSource.source\",columns=\"dow\",values=\"totals.transactionRevenue\",aggfunc=lambda x:x.sum())\nfv = fv.sort_values(by=0, ascending=False)[:6]\n\ntrace = go.Heatmap(z=[fv.values[0],fv.values[1],fv.values[2], fv.values[3],fv.values[4],fv.values[5]],\n                   x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday','Sunday'],\n                   y=fv.index.values, colorscale='Reds'\n                  )\n\ndata=[trace]\nlayout = go.Layout(dict(\n    title='Total Revenue by Traffic Source<br>(day of week)'),\n                margin  = dict(l = 150\n                                      )  )\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e892fe9b04512ed0e6214a5fd8422b165229f1c","_kg_hide-input":true},"cell_type":"code","source":"PieChart(\"trafficSource.source\", \"Traffic Source\", 5)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f5c9a521e35fc3322898af6b5f57a9b5b8c13cc5"},"cell_type":"markdown","source":"**Although youtube creates a huge traffic it does not have a signifact effect on total revenues**\n\n**Google plex that create only 8.9% total traffic contributes to 41.5% of total revenue.**\n\n**Let's apply same steps on source medium in terms of months.  **"},{"metadata":{"trusted":true,"_uuid":"a20a895e35c6696eb1d8f2d5b5457cae293f7d21","_kg_hide-input":true},"cell_type":"code","source":"fv = df.pivot_table(index=\"trafficSource.medium\",columns=\"month\",values=\"totals.transactionRevenue\",aggfunc=lambda x:x.sum())\nfv = fv.sort_values(by=1, ascending=False)[:5]\n\ntrace = go.Heatmap(z=[fv.values[0],fv.values[1],fv.values[2], fv.values[3],fv.values[4]],\n                   x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],\n                   y=fv.index.values, colorscale='Reds'\n                  )\n\ndata=[trace]\nlayout = go.Layout(dict(\n    title='Total Revenue by Source Medium<br>(months)'),\n                margin  = dict(l = 150\n                                      ))\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"572f402ba4fef70e4284c9817def3d3a35363260","_kg_hide-input":true},"cell_type":"code","source":"PieChart(\"trafficSource.medium\", \"Source Medium\", 5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3eaeb6ba7291c9489a6b03a7a247e5c73752e18a"},"cell_type":"markdown","source":"**Let's finalize the work with a world map!**"},{"metadata":{"trusted":true,"_uuid":"f0e356f3b123dfcb1a970301985f57e6ebf66d48","_kg_hide-input":true},"cell_type":"code","source":"count_geo = df.groupby('geoNetwork.country')['geoNetwork.country'].count()\n\ndata = [dict(\n        type = 'choropleth',\n        locations = count_geo.index,\n        locationmode = 'country names',\n        z = count_geo.values,\n        text = count_geo.index,\n        colorscale = [[0,\"rgb(5, 10, 172)\"],[0.35,\"rgb(40, 60, 190)\"],[0.5,\"rgb(70, 100, 245)\"],\n            [0.6,\"rgb(90, 120, 245)\"],[0.7,\"rgb(106, 137, 247)\"],[1,\"rgb(220, 220, 220)\"]],\n        autocolorscale = False,\n        reversescale = True,\n        marker = dict(\n            line = dict (\n                color = 'rgb(180,180,180)',\n                width = 0.5\n            ) ),\n        colorbar = dict(\n            autotick = False,\n            tickprefix = '',\n            title = 'Number of calls'),\n      ) ]\n\nlayout = dict(\n    title = 'Number of Visits by Country',\n    geo = dict(\n        showframe = False,\n        showcoastlines = True,\n        projection = dict(\n            type = 'Mercator'\n        )\n    )\n)\n\nfig = dict(data=data, layout=layout )\npy.iplot(fig, validate=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2af097ecde8e9f61f63932f05acdc12d191cd1f3","_kg_hide-input":true},"cell_type":"code","source":"count = df[['geoNetwork.continent','totals.transactionRevenue',\n            'day']].groupby('geoNetwork.continent', as_index=False)['day'].\\\n                    count().sort_values(by='day', ascending=False)\n\nsumrev = df[['geoNetwork.continent','totals.transactionRevenue']].groupby('geoNetwork.continent', \n                                                       as_index=False)['totals.transactionRevenue'].\\\n                    sum().sort_values(by='totals.transactionRevenue', ascending=False)\n\nmeanrev = df[['geoNetwork.continent','totals.transactionRevenue']].groupby('geoNetwork.continent', \n                                                       as_index=False)['totals.transactionRevenue'].\\\n                    mean().sort_values(by='totals.transactionRevenue', ascending=False)\n\ntrace = [\n    go.Bar(x=count['geoNetwork.continent'],\n    y=count['day'],\n                opacity = 0.7,\n                 name=\"COUNT\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='aqua')\n                ),\n    go.Bar(x=sumrev['geoNetwork.continent'],\n    y=sumrev['totals.transactionRevenue'],\n                 visible=False,\n                 opacity = 0.7,\n                 name = \"TOTAL\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='navy')\n                ),\n    go.Bar(x=meanrev['geoNetwork.continent'],\n    y=meanrev['totals.transactionRevenue'],\n                 visible=False,\n                opacity = 0.7,\n                 name = \"MEAN\",\n                 hoverinfo=\"y\",\n                 marker=dict(line=dict(width=1.6),\n                            color='red')\n                \n                )\n]\n\nlayout = go.Layout(title = 'Revenue Statistics of Continents',\n    paper_bgcolor = 'rgb(240, 240, 240)',\n     plot_bgcolor = 'rgb(240, 240, 240)',\n    autosize=True,\n                   xaxis=dict(title=\"\",\n                             titlefont=dict(size=20),\n                             tickmode=\"linear\")\n                  )\n\nupdatemenus = list([\n    dict(\n    buttons=list([\n        dict(\n            args = [{'visible': [True, False, False]}],\n            label=\"Count\",\n            method='update',\n        ),\n        dict(\n            args = [{'visible': [False, True, False]}],\n            label=\"Total Revenue\",\n            method='update',\n        ),\n        dict(\n            args = [{'visible': [False, False, True]}],\n            label=\"Mean Revenue\",\n            method='update',\n        ),\n        \n    ]),\n        direction=\"down\",\n        pad = {'r':10, \"t\":10},\n        x=0.1,\n        y=1.25,\n        yanchor='top',\n    )\n])\n\nlayout['updatemenus'] = updatemenus\n\nfig = dict(data=trace, layout=layout)\npy.iplot(fig)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}