Ejemplo n.º 1
0
 def test_subplot_1_in_constructor(self):
     layout = go.Layout(xaxis1=go.layout.XAxis(title={"text": "xaxis 1"}))
     self.assertEqual(layout.xaxis1.title.text, "xaxis 1")
Ejemplo n.º 2
0
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])

x = points[:, 0]
y = points[:, 1]

z = np.polyfit(x, y, 3)
f = np.poly1d(z)

x_new = np.linspace(0, 10, 50)
y_new = f(x_new)

trace1 = go.Scatter(x=x,
                    y=y,
                    mode='markers',
                    name='Data',
                    marker=dict(size=12))

trace2 = go.Scatter(x=x_new, y=y_new, mode='lines', name='Fit')

annotation = go.Annotation(x=6,
                           y=-4.5,
                           text='$0.43X^3 - 0.56X^2 + 16.78X + 10.61$',
                           showarrow=False)

layout = go.Layout(title='Polynomial Fit in Python', annotations=[annotation])

data = [trace1, trace2]
fig = go.Figure(data=data, layout=layout)

py.iplot(fig, filename='interpolation-and-extrapolation')
val = telcom["Churn"].value_counts().values.tolist()

# Plot customer churn attrition, meaning churn/non churn proportion
trace = go.Pie(labels = lab ,
               values = val ,
               marker = dict(colors =  [ 'royalblue' ,'orange'],
                             line = dict(color = "white",
                                         width =  1.3)
                            ),
               rotation = 90,
               hoverinfo = "label+value+text",
               hole = .5
              )
layout = go.Layout(dict(title = "Customer attrition in data",
                        plot_bgcolor  = "rgb(243,243,243)",
                        paper_bgcolor = "rgb(243,243,243)",
                       )
                  )
data = [trace]
fig = go.Figure(data = data,layout = layout)
py.iplot(fig)




###### Distribution of every covariate with respect to each value of churn. 

# Function for pie plot for customer attrition types
def plot_pie(column) :
    
    trace1 = go.Pie(values  = churn[column].value_counts().values.tolist(),
Ejemplo n.º 4
0
def crunch_graphical_model(pgm_path, path_datasets):
    from networkx.drawing.nx_agraph import graphviz_layout
    import plotly.graph_objs as go
    from plotly.offline import plot

    def build_graph(series):
        G = nx.DiGraph()

        node_labels = dict()

        for node_id in xrange(series.shape[1]):
            probs = series[:, node_id]

            G.add_node(node_id,
                       attr_dict=dict(color=max(probs),
                                      probs='<br>'.join([
                                          '%2.3f : %s' % (y, x)
                                          for x, y in it.izip(columns, probs)
                                      ])))
            parent = get_parent(node_id)
            if parent is not None:
                G.add_edge(parent, node_id)

            node_labels[node_id] = node_id

        return G

    def build_edges(_G):
        edge_trace = go.Scatter(x=[],
                                y=[],
                                line=go.Line(width=0.5, color='#999'),
                                hoverinfo='none',
                                mode='lines',
                                name='edges')

        for edge in _G.edges():
            x0, y0 = pos[edge[0]]
            x1, y1 = pos[edge[1]]
            edge_trace['x'] += [x0, x1, None]
            edge_trace['y'] += [y0, y1, None]

        return edge_trace

    def build_nodes(_G, _generation):
        nodes = _G.nodes(data=True)

        _node_trace = go.Scatter(
            x=[pos[node[0]][0] for node in nodes],
            y=[pos[node[0]][1] for node in nodes],
            name='gen %d' % _generation,
            text=[x[1]['probs'] for x in nodes],
            mode='markers',
            visible=True if _generation == 0 else 'legendonly',
            hoverinfo='text',
            marker=go.Marker(
                showscale=True,
                color=[x[1]['color'] for x in nodes],
                colorscale='RdBu',
                colorbar=dict(
                    title='Assurance',
                    xpad=100,
                ),
                cmin=0.,  # minimum color value
                cmax=1.,  # maximum color value
                cauto=False,  # do not automatically fit color values
                reversescale=False,
                size=15,
                line=dict(width=2)))
        return _node_trace

    sep = '\\' if os.name == 'nt' else '/'

    dataset_name = pgm_path.split(sep)[-1].split('_')[0]

    dataset = load_dataframe(
        os.path.join(path_datasets, dataset_name + '.arff'))
    columns = dataset.columns
    n_columns = dataset.shape[1]
    del dataset

    data = []

    with open(pgm_path, 'r') as f:
        csv_w = csv.reader(f, delimiter=',', quotechar='\"')
        for generation, line in enumerate(csv_w):
            series = np.array(line, dtype=np.float).reshape(
                n_columns,
                -1)  # each row is an attribute, each column a generation

            G = build_graph(series)

            pos = graphviz_layout(G, root=0, prog='dot')

            if generation == 0:
                data.append(build_edges(G))

            node_trace = build_nodes(G, generation)
            data += [node_trace]

        fig = go.Figure(
            data=go.Data(data),
            layout=go.Layout(
                title='Probabilistic Graphical Model<br>Dataset %s' %
                dataset_name,
                titlefont=dict(size=16),
                showlegend=True,
                hovermode='closest',
                xaxis=go.XAxis(showgrid=False,
                               zeroline=False,
                               showticklabels=False),
                yaxis=go.YAxis(showgrid=False,
                               zeroline=False,
                               showticklabels=False),
            ))

        plot(fig, filename=pgm_path.split(sep)[-1] + '.html')
Ejemplo n.º 5
0
def plot_perps_map(perps, date_range, country):
    country = '' or country
    df = terrorism[terrorism['gname'].isin(perps)
                   & (terrorism['country_txt'] == country)
                   & terrorism['date'].between(mydates[date_range[0]],
                                               mydates[date_range[1]])]

    return {
        'data': [
            go.Scattergeo(
                lon=df[df['gname'] == perp]['longitude'],
                lat=df[df['gname'] == perp]['latitude'],
                name=perp,
                hoverinfo='text',
                showlegend=True,
                marker={
                    'size': 9,
                    'line': {
                        'width': .2,
                        'color': '#cccccc'
                    }
                },
                hovertext=df[df['gname'] == perp]['city'].astype(str) + ', ' +
                df[df['gname'] == perp]['country_txt'].astype(str) + '<br>' + [
                    datetime.datetime.strftime(d, '%d %b, %Y')
                    for d in df[df['gname'] == perp]['date']
                ] + '<br>' + 'Perpetrator: ' +
                df[df['gname'] == perp]['gname'].astype(str) + '<br>' +
                'Target: ' + df[df['gname'] == perp]['target1'].astype(str) +
                '<br>' + 'Deaths: ' +
                df[df['gname'] == perp]['nkill'].astype(str) + '<br>' +
                'Injured: ' + df[df['gname'] == perp]['nwound'].astype(str) +
                '<br><br>' + [
                    '<br>'.join(textwrap.wrap(x, 40))
                    if not isinstance(x, float) else ''
                    for x in df[df['gname'] == perp]['summary']
                ]) for perp in perps
        ],
        'layout':
        go.Layout(
            title='Terrorist Attacks in ' + country + '  ' +
            datetime.datetime.strftime(mydates[date_range[0]], '%b, %Y') +
            ' - ' +
            datetime.datetime.strftime(mydates[date_range[1]], '%b, %Y') +
            '<br>' + '<br>'.join(textwrap.wrap(', '.join(perps), 110)),
            font={'family': 'Palatino'},
            titlefont={'size': 22},
            paper_bgcolor='#eeeeee',
            plot_bgcolor='#eeeeee',
            width=1420,
            height=650,
            annotations=[{
                'text': '<a href="https://www.twitter.com">@eliasdabbas</a>',
                'x': .2,
                'y': -.1,
                'showarrow': False
            }, {
                'text': 'Data: START Consortium',
                'x': .2,
                'y': -.13,
                'showarrow': False
            }],
            geo={
                'showland': True,
                'landcolor': '#eeeeee',
                'countrycolor': '#cccccc',
                'showsubunits': True,
                'subunitcolor': '#cccccc',
                'subunitwidth': 5,
                'showcountries': True,
                'oceancolor': '#eeeeee',
                'showocean': True,
                'showcoastlines': True,
                'showframe': False,
                'coastlinecolor': '#cccccc',
                'lonaxis': {
                    'range':
                    [df['longitude'].min() - 1, df['longitude'].max() + 1]
                },
                'lataxis': {
                    'range':
                    [df['latitude'].min() - 1, df['latitude'].max() + 1]
                }
            })
    }
Ejemplo n.º 6
0
bitterness = go.Bar(
    x=beers,
    y=ibu_values,
    name=label1,
    marker={'color':color1}
)
alcohol = go.Bar(
    x=beers,
    y=abv_values,
    name=label2,
    marker={'color':color2}
)

beer_data = [bitterness, alcohol]
beer_layout = go.Layout(
    barmode='group',
    title = mytitle
)

beer_fig = go.Figure(data=beer_data, layout=beer_layout)


########### Initiate the app
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
app.title=tabtitle

########### Set up the layout
app.layout = html.Div(children=[
    html.H1(myheading),
    dcc.Graph(
Ejemplo n.º 7
0
                  'value': 'South America'
              }],
              value='Europe'),
 html.Br(),
 html.Hr(style={'color': '#7FDBFF'}),
 html.H3('Bar chart', style={'color': '#df1e56'}),
 html.Div(
     'This bar chart represent the number of confirmed cases in the first 20 states of the US.'
 ),
 dcc.Graph(id='graph2',
           figure={
               'data':
               data_barchart,
               'layout':
               go.Layout(title='Corona Virus Confirmed Cases in The US',
                         xaxis={'title': 'States'},
                         yaxis={'title': 'Number of confirmed cases'})
           }),
 html.Hr(style={'color': '#7FDBFF'}),
 html.H3('Stack bar chart', style={'color': '#df1e56'}),
 html.Div(
     'This stack bar chart represent the CoronaVirus deaths, recovered and under treatment of all reported first 20 countries except China.'
 ),
 dcc.Graph(
     id='graph3',
     figure={
         'data':
         data_stackbarchart,
         'layout':
         go.Layout(
             title='Corona Virus Cases in the first 20 country expect China',
Ejemplo n.º 8
0
import plotly.graph_objs as go

xvals = ['foo', 'bar', 'baz']
yvals = [5, 4, 6]

bar_data = go.Bar(x=xvals, y=yvals)
basic_layout = go.Layout(title="A Bar Graph")
fig = go.Figure(data=bar_data, layout=basic_layout)

fig.show()
Ejemplo n.º 9
0
                                     y=df['wheels'],
                                     dy=1,
                                     mode='markers',
                                     marker={
                                         'size': 12,
                                         'color': 'rgb(51,204,153)',
                                         'line': {
                                             'width': 2
                                         }
                                     })
                      ],
                      'layout':
                      go.Layout(title='Wheels & Colors Scatterplot',
                                xaxis={'title': 'Color'},
                                yaxis={
                                    'title': '# of Wheels',
                                    'nticks': 3
                                },
                                hovermode='closest')
                  })
    ],
             style={
                 'width': '30%',
                 'float': 'left'
             }),
    html.Div([html.Pre(id='hover-data', style={'paddingTop': 35})],
             style={'width': '30%'})
])


@app.callback(Output('hover-data', 'children'),
Ejemplo n.º 10
0
def update_graph_emission(dem_slider, insulation_standards, insulation_standards_ref, refurbishment_rate, oil, gas, direct_elec, heating_pump, wood, thermal):

	new_energy_mix = pd.DataFrame({

	    'year': [2050], 
	    'coal' : 0,
	    'oil': 0.01*oil, 
	    'gas': 0.01*gas,
	   	'direct_elec' : 0.01*direct_elec, 
	    'heating_pump': 0.01*heating_pump, 
	    'wood': 0.01*wood, 
	    'thermal': 0.01*thermal

	})

	new_sre = model.update_sre(old_sre, dem_slider)

	new_heat_need = model.update_heatneed(refurbishment_rate, dem_slider, insulation_standards, insulation_standards_ref)

	energy_mix = model.update_energy_mix(new_energy_mix)

	updated_coal_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['coal']/efficiency['coal'])
	updated_oil_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['oil']/efficiency['oil'])
	updated_gas_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['gas']/efficiency['gas'])
	updated_direct_elec_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['direct_elec']/efficiency['direct_elec'])
	updated_heat_pump_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['heating_pump']/efficiency['heating_pump'])
	updated_wood_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['wood']/efficiency['wood'])
	updated_thermal_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['thermal']/efficiency['thermal'])

	total_cons = list(updated_coal_cons+updated_oil_cons+updated_gas_cons+updated_direct_elec_cons+updated_heat_pump_cons+updated_wood_cons+updated_thermal_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons, updated_thermal_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons, updated_thermal_cons))

	co2_mix = pd.DataFrame({
    
    'coal': energy_mix['coal']*CO2_emissions['coal'],
    'oil': energy_mix['oil']*CO2_emissions['oil'],
    'gas': energy_mix['gas']*CO2_emissions['gas'],
    'direct_elec': energy_mix['direct_elec']*CO2_emissions['direct_elec'],
    'heating_pump': energy_mix['heating_pump']*CO2_emissions['heating_pump'],
    'wood': energy_mix['wood']*CO2_emissions['wood'],
    'thermal': energy_mix['thermal']*CO2_emissions['thermal']
    
	})

	updated_emissions = list(co2_mix.sum(axis=1)*total_cons)
	updated_emissions = list(np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_emissions))

	new_population = model.update_pop(dem_slider, population[-1])
	emissions_SE2050 = list(0.5*item*1e-3 for item in (population+new_population))

	emis = go.Scatter(
		x = year,
		y = city_emissions + updated_emissions,
		mode = 'lines',
		line = dict(width = 0.5, color = 'rgb(0,0,0)'),
		name = 'Émissions de CO2',
		fill = 'tozeroy'
		)

	emis_target = go.Scatter(
		x = year,
		y = emissions_SE2050,
		mode = 'lines',
		line = dict(width = 1.5, color = 'red'),
		name = 'Objectif SE 2050'
		)

	layout = go.Layout(
		margin = dict(t=20, l=100),
		yaxis = {'title': 'Millions de t.eq CO2', 'range':[0, 1.15*max(city_emissions)]},
		xaxis = dict(range = [2001, 2051])
		)

	data = [emis, emis_target]
	figure = dict(data = data, layout = layout)
	return figure
Ejemplo n.º 11
0
################################################

#HEATMAP & LINE CHART
l_trend = go.Layout(height=500,
                    margin={
                        "r": 10,
                        "t": 10,
                        "l": 10,
                        "b": 10
                    },
                    template="plotly_dark",
                    paper_bgcolor=main_color,
                    plot_bgcolor=main_color,
                    yaxis={"tickfont": {
                        "size": 10
                    }},
                    xaxis={"tickfont": {
                        "size": 10
                    }},
                    legend={
                        'x': 0.01,
                        'y': 0.98,
                        'font': {
                            'size': 10
                        },
                        'itemclick': 'toggleothers'
                    },
                    dragmode=False)

#CHART LAYOUTS
Ejemplo n.º 12
0
def update_graph_conso(dem_slider, insulation_standards, refurbishment_rate, insulation_standards_ref, oil, gas, direct_elec, heating_pump, wood, thermal):

	new_energy_mix = pd.DataFrame({

	    'year': [2050], 
	    'coal' : 0,
	    'oil': 0.01*oil, 
	    'gas': 0.01*gas,
	   	'direct_elec' : 0.01*direct_elec, 
	    'heating_pump': 0.01*heating_pump, 
	    'wood': 0.01*wood, 
	    'thermal': 0.01*thermal

	})

	new_sre = model.update_sre(old_sre, dem_slider)

	new_heat_need = model.update_heatneed(refurbishment_rate, dem_slider, insulation_standards, insulation_standards_ref)

	energy_mix = model.update_energy_mix(new_energy_mix)
	new_population = model.update_pop(dem_slider, population[-1])
	consumption_SE2050 = list((514)*3600*24*365*1e3*item*1e-12 for item in (population+new_population))  # 514 W représente la valeur cible de la société à 2000W à l'horizon 2050 cf. SIA 2000W
	
	y1 = list(coal_cons)
	y2 = list(coal_cons+oil_cons for coal_cons, oil_cons in zip(coal_cons, oil_cons))
	y3 = list(coal_cons+oil_cons+gas_cons for coal_cons, oil_cons, gas_cons in zip(coal_cons, oil_cons, gas_cons))
	y4 = list(coal_cons+oil_cons+gas_cons+2.9*direct_elec_cons for coal_cons, oil_cons, gas_cons, direct_elec_cons in zip(coal_cons, oil_cons, gas_cons, direct_elec_cons))
	y5 = list(coal_cons+oil_cons+gas_cons+2.9*direct_elec_cons+2.9*heat_pump_cons for coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons in zip(coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons))
	y6 = list(coal_cons+oil_cons+gas_cons+2.9*direct_elec_cons+2.9*heat_pump_cons+wood_cons for coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons, wood_cons in zip(coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons, wood_cons))
	y7 = list(coal_cons+oil_cons+gas_cons+2.9*direct_elec_cons+2.9*heat_pump_cons+wood_cons+thermal_cons for coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons, wood_cons, thermal_cons in zip(coal_cons, oil_cons, gas_cons, direct_elec_cons, heat_pump_cons, wood_cons, thermal_cons))

	
	updated_coal_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['coal']/efficiency['coal'])
	updated_coal_cons= np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_coal_cons)	
	updated_oil_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['oil']/efficiency['oil'])
	updated_oil_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_oil_cons)
	updated_gas_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['gas']/efficiency['gas'])
	updated_gas_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_gas_cons)
	updated_direct_elec_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['direct_elec']/efficiency['direct_elec'])
	updated_direct_elec_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_direct_elec_cons)
	updated_heat_pump_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['heating_pump']/efficiency['heating_pump'])
	updated_heat_pump_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_heat_pump_cons)
	updated_wood_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['wood']/efficiency['wood'])
	updated_wood_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_wood_cons)
	updated_thermal_cons = list(1e-6*np.asarray(new_sre)*np.asarray(new_heat_need)*energy_mix['thermal']/efficiency['thermal'])
	updated_thermal_cons = np.random.normal(loc=1, scale=0.03, size=35)*np.asanyarray(updated_thermal_cons)

	
	y11 = list(updated_coal_cons)
	y21 = list(updated_coal_cons+updated_oil_cons for updated_coal_cons, updated_oil_cons in zip(updated_coal_cons, updated_oil_cons))
	y31 = list(updated_coal_cons+updated_oil_cons+updated_gas_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons))
	y41 = list(updated_coal_cons+updated_oil_cons+updated_gas_cons+2.9*updated_direct_elec_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons))
	y51 = list(updated_coal_cons+updated_oil_cons+updated_gas_cons+2.9*updated_direct_elec_cons+2.9*updated_heat_pump_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons))
	y61 = list(updated_coal_cons+updated_oil_cons+updated_gas_cons+2.9*updated_direct_elec_cons+2.9*updated_heat_pump_cons+updated_wood_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons))
	y71 = list(updated_coal_cons+updated_oil_cons+updated_gas_cons+2.9*updated_direct_elec_cons+2.9*updated_heat_pump_cons+updated_wood_cons+updated_thermal_cons for updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons, updated_thermal_cons in zip(updated_coal_cons, updated_oil_cons, updated_gas_cons, updated_direct_elec_cons, updated_heat_pump_cons, updated_wood_cons, updated_thermal_cons))

	coal = go.Scatter(
	    x = year,
	    y = y1+y11,
	    mode = 'lines',
	    line = dict(width = 0.2),
	    name = 'Charbon',
	    fill = 'tozeroy'
	)

	oil = go.Scatter(
	    x = year,
	    y = y2+y21,
	    mode = 'lines',
	    line = dict(width = 0.2, color = 'rgb(100,100,100)'),
	    name = 'Mazout',
	    fill = 'tonexty'
	)

	gas = go.Scatter(
	    x = year,
	    y = y3+y31,
	    mode = 'lines',
	    line = dict(width = 0.2, color = 'rgb(200,200,200)'),
	    name = 'Gaz',
	    fill = 'tonexty'
	)

	direct_elec = go.Scatter(
	    x = year,
	    y = y4+y41,
	    mode = 'lines',
	    line = dict(width = 0.2, color = '#F6F60F'),
	    name = 'Électricité directe',
	    fill = 'tonexty'
	)

	heating_pump = go.Scatter(
	    x = year,
	    y = y5+y51,
	    mode = 'lines',
	    line = dict(width = 0.2),
	    name = 'PAC',
	    fill = 'tonexty'
	)

	wood = go.Scatter(
	    x = year,
	    y = y6+y61,
	    mode = 'lines',
	    line = dict(width = 0.2, color = '#B26633'),
	    name = 'Bois',
	    fill = 'tonexty'
	)

	thermal = go.Scatter(
	    x = year,
	    y = y7+y71,
	    mode = 'lines',
	    line = dict(width = 0.2, color = '#50BD4D'),
	    name = 'Renouvelables',
	    fill = 'tonexty'
	)

	cons_target = go.Scatter(
	    x = year,
	    y = consumption_SE2050,
	    mode = 'lines',
	    line = dict(width = 1.5, color = 'red'),
	    name = 'SE 2050'
	)


	layout = go.Layout(
	    legend = dict(x = 1.1, y=0.25),
	    xaxis = dict(range=[2001, 2051]),
	    yaxis = dict(title = 'Consommation énergie primaire (TJ)', range=[0, 1.15*max(y71)]),
	    margin = dict(t=20, l=100)
	)

	data = [coal, oil, gas, direct_elec, heating_pump, wood, thermal, cons_target]
	figure = dict(data = data, layout = layout)
	return figure

	print(global_eff)
Ejemplo n.º 13
0
def tn_tp(tn_val, tp_val, current_df):
    min_tn = tn_val[0]
    max_tn = tn_val[1]
    min_tp = tp_val[0]
    max_tp = tp_val[1]

    if max_tn == 0:
        max_tn = np.max(current_df["Total Nitrogen (ug/L)"])

    if max_tp == 0:
        max_tp = np.max(current_df["Total Phosphorus (ug/L)"])

    dat = current_df[(current_df["Total Nitrogen (ug/L)"] >= min_tn)
                     & (current_df["Total Nitrogen (ug/L)"] <= max_tn) &
                     (current_df["Total Phosphorus (ug/L)"] >= min_tp) &
                     (current_df["Total Phosphorus (ug/L)"] <= max_tp)]
    MC_conc = dat['Microcystin (ug/L)']
    # make bins
    b1 = dat[MC_conc <= USEPA_LIMIT]
    b2 = dat[(MC_conc > USEPA_LIMIT) & (MC_conc <= WHO_LIMIT)]
    b3 = dat[MC_conc > WHO_LIMIT]

    data = [
        go.Scatter(
            x=np.log(b1["Total Nitrogen (ug/L)"]),
            y=np.log(b1["Total Phosphorus (ug/L)"]),
            mode='markers',
            name="<USEPA",
            text=current_df["Body of Water Name"],
            marker=dict(
                size=8,
                color="green",  #set color equal to a variable
            )),
        go.Scatter(
            x=np.log(b2["Total Nitrogen (ug/L)"]),
            y=np.log(b2["Total Phosphorus (ug/L)"]),
            mode='markers',
            name=">USEPA",
            text=current_df["Body of Water Name"],
            marker=dict(
                size=8,
                color="orange"  #set color equal to a variable
            )),
        go.Scatter(
            x=np.log(b3["Total Nitrogen (ug/L)"]),
            y=np.log(b3["Total Phosphorus (ug/L)"]),
            mode='markers',
            name=">WHO",
            text=current_df["Body of Water Name"],
            marker=dict(
                size=8,
                color="red",  #set color equal to a variable
            ))
    ]

    layout = go.Layout(showlegend=True,
                       xaxis=dict(title='log TN'),
                       yaxis=dict(title="log TP"),
                       hovermode='closest')

    return (go.Figure(data=data, layout=layout))
Ejemplo n.º 14
0
    def setUp(self):
        # Construct initial scatter object
        self.layout = go.Layout()

        pio.templates.default = None
Ejemplo n.º 15
0
    diff = _max - _min
    a = np.arctanh(-.5)
    b = np.arctanh(.5)
    alpha = (b - a) / diff
    beta = b - (alpha * _max)
    norm_scores = np.tanh(alpha * scores + beta)

    ex_data[:, 2] = norm_scores

    data.append(ex_data)

data = np.concatenate(data, axis=0)

norm = go.Box(y=data[data[:, 1] == 1][:, 2],
              x=[ex_map[int(i)] for i in data[data[:, 1] == 1][:, 0]],
              name='normal',
              marker=dict(color='#2ecc71'))

anom = go.Box(y=data[data[:, 1] == 0][:, 2],
              x=[ex_map[int(i)] for i in data[data[:, 1] == 0][:, 0]],
              name='anomalous',
              marker=dict(color='#c0392b'))

layout = go.Layout(
    title='AnoGAN Scores on 3 Time Step Anomaly Detection Normalized',
    yaxis=dict(title='Score'),
    boxmode='group')

fig = go.Figure(data=(norm, anom), layout=layout)
py.plot(fig, filename='sad/mnist/3ts_ano_gan_scores_norm_cnn')
Ejemplo n.º 16
0
"""! 
@brief Example 16
@details librosa beattracking example: extract tempo and spectral centroid for
songs from different musical genres
@author Theodoros Giannakopoulos {[email protected]}
"""
import scipy.io.wavfile as wavfile, utilities as ut
import glob, os, librosa, plotly, numpy as np, plotly.graph_objs as go
from pyAudioAnalysis.audioFeatureExtraction import mtFeatureExtraction as mt

layout = go.Layout(title='Beat and spectral centroid distributions',
                   xaxis=dict(title='Tempo (bpms)', ),
                   yaxis=dict(title='Spectral Centroid Mean', ))


def get_dir_features(dir_name):
    feats = []
    for f in glob.glob(os.path.join(dir_name, "*.wav")):
        [Fs, s] = wavfile.read(f)
        tempo, _ = librosa.beat.beat_track(y=s, sr=Fs)
        f, _, fn = mt(s, Fs, int(1.0 * Fs), int(1.0 * Fs), int(0.1 * Fs),
                      int(0.1 * Fs))
        feats.append(
            [tempo,
             np.mean(f[fn.index("spectral_centroid_mean")], axis=0)])
    return np.array(feats)


if __name__ == '__main__':
    g_paths = glob.glob("../data/musical_genres_small/*/")
    g_names = [p.split('/')[-2] for p in g_paths]
Ejemplo n.º 17
0
# range slider options
st['Date'] = pd.to_datetime(st.Date)
#Divide dates into equal parts

dates = [
    '2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17', '2016-02-17',
    '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17'
]

# Step 3. Create a plotly figure
trace_1 = go.Scatter(x=st.Date,
                     y=st['AAPL.High'],
                     name='AAPL HIGH',
                     line=dict(width=2, color='rgb(229, 151, 50)'))
layout = go.Layout(title='Time Series Plot', hovermode='closest')
fig = go.Figure(data=[trace_1], layout=layout)

# Step 4. Create a Dash layout
app.layout = html.Div([
    # a header and a paragraph
    html.Div([html.H1("Apple Stock Price"),
              html.P("Time Series Analysis")],
             style={
                 'padding': '50px',
                 'backgroundColor': '#3aaab2'
             }),
    # adding a plot
    dcc.Graph(id='plot', figure=fig),
    # dropdown
    html.P(
Ejemplo n.º 18
0
def graphQuery(gene, study, project):
    wt_time = []
    wt_state = []
    mut_time = []
    mut_state = []
    wtdf = KaplanMeierFitter()
    mutdf = KaplanMeierFitter()

    rows = getData(project.lower(), study, gene.upper())
    for (barcode, days, vital, mutation) in rows:
        if mutation == 'WT':
            #There are negative day values, set to 0
            if days >= 0:
                wt_time.append(days)
            else:
                wt_time.append(0)
            if vital == 'Alive':
                wt_state.append(1)
            else:
                wt_state.append(0)
        elif mutation == 'Mutant':
            if days >= 0:
                mut_time.append(days)
            else:
                mut_time.append(0)
            if vital == 'Alive':
                mut_state.append(1)
            else:
                mut_state.append(0)
        else:
            print "Neither WT nor Mutant"

    wtdf.fit(wt_time, event_observed=wt_state)
    mutdf.fit(mut_time, event_observed=mut_state)

    #In lifelines, once the fit is done, survival_function_ and confidence_interval are pandas dataframes
    wildtypeupper = go.Scatter(
        name='WT Upper Bound',
        y=wtdf.confidence_interval_['KM_estimate_upper_0.95'],
        x=wtdf.confidence_interval_.index,
        mode='lines',
        marker=dict(color="444"),
        line=dict(width=0),
        fillcolor='rgba(255,165,0,0.3)',
        fill='tonextx')
    wildtypedata = go.Scatter(y=wtdf.survival_function_['KM_estimate'],
                              x=wtdf.survival_function_.index,
                              mode='lines+markers',
                              name='Wild Type',
                              line=dict(color='rgb(255,165,0)'))
    wildtypelower = go.Scatter(
        name='WT Lower Bound',
        y=wtdf.confidence_interval_['KM_estimate_lower_0.95'],
        x=wtdf.confidence_interval_.index,
        mode='lines',
        marker=dict(color="444"),
        line=dict(width=0),
        fillcolor='rgba(255,165,0,0.3)',
        fill='tonextx')
    mutantupper = go.Scatter(
        name='Mut Upper Bound',
        y=mutdf.confidence_interval_['KM_estimate_upper_0.95'],
        x=mutdf.confidence_interval_.index,
        mode='lines',
        marker=dict(color="444"),
        line=dict(width=0),
        fillcolor='rgba(70,130,180,0.3)',
        fill='tonextx')
    mutantdata = go.Scatter(y=mutdf.survival_function_['KM_estimate'],
                            x=mutdf.survival_function_.index,
                            mode='lines+markers',
                            name='Mutant',
                            line=dict(color='rgb(70,130,180)'))
    mutantlower = go.Scatter(
        name='Mut Lower Bound',
        y=mutdf.confidence_interval_['KM_estimate_lower_0.95'],
        x=mutdf.confidence_interval_.index,
        mode='lines',
        marker=dict(color="444"),
        line=dict(width=0),
        fillcolor='rgba(70,130,180,0.3)',
        fill='tonexty')
    layout = go.Layout(title=(("Cohort: %s  Gene: %s ") %
                              (study, gene.upper())),
                       xaxis=dict(title='Time'),
                       yaxis=dict(title='Survival Probability'))

    return go.Figure(data=[
        wildtypedata, wildtypelower, wildtypeupper, mutantdata, mutantlower,
        mutantupper
    ],
                     layout=layout)
Ejemplo n.º 19
0
def encode_image(image_file):
    encoded = base64.b64encode(open(image_file, 'rb').read())
    return 'data:image/png;base64,{}'.format(encoded.decode())


ScatterGraph = dcc.Graph(id='wheels-plot',
                         figure=dict(data=[
                             go.Scatter(x=df['color'],
                                        y=df['wheels'],
                                        dy=1,
                                        mode='markers',
                                        marker={'size': 12})
                         ],
                                     layout=go.Layout(
                                         title='Hover Data Visualization',
                                         xaxis=dict(title='Color'),
                                         yaxis=dict(title='Wheels'),
                                         hovermode='closest')))

app.layout = html.Div([
    html.Div(ScatterGraph),
    html.Div(html.Img(id='hover-data', src='children', height=300))
])


@app.callback(Output('hover-data', 'src'), [Input('wheels-plot', 'clickData')])
def callback_image(hoverData):
    wheel = hoverData['points'][0]['y']
    color = hoverData['points'][0]['x']
    path = 'data/Images/'
    file = df[(df['wheels'] == wheel)
Ejemplo n.º 20
0
    def f(viz='X-Y',
          colx='',
          coly='',
          colz='',
          colw=10,
          na=False,
          asc='',
          source=df):
        if (viz == 'X-Y'):
            print(
                '{}: {:0.1%} null ({:d} out of {:d})'\
                    .format(
                        colx
                        , source[colx].isnull().sum() / source.shape[0]
                        , source[colx].isnull().sum()
                        , source.shape[0]
                    )
                )
            print(
                '{}: {:0.1%} null ({:d} out of {:d})'\
                    .format(
                        colz
                        , source[colz].isnull().sum() / source.shape[0]
                        , source[colz].isnull().sum()
                        , source.shape[0]
                    )
                )

            temp = source
            if na:
                temp = temp.fillna(-1000)

            if (coly == 'unaggregrated'):
                grouped = temp.loc[:, [colx, colz]].set_index(colx)
                grouped.columns = pd.MultiIndex.from_product([[colz], [coly]])
            if (coly in ['count', 'sum', 'mean', 'std', 'max', 'min']):
                grouped = temp.groupby(colx).agg({colz: [coly]})
            elif (coly == 'uniques'):
                grouped = temp.groupby(colx).apply(lambda g: pd.Series(
                    g[colz].unique().size,
                    index=pd.MultiIndex.from_product([[colz], [coly]])))
            # print(grouped.head())

            trace = go.Scattergl(x=grouped.index,
                                 y=grouped[colz][coly],
                                 name=coly + ' of ' + colz + ' vs ' + colx,
                                 mode=colw)
            layout = go.Layout(title=coly + ' of ' + colz + ' vs ' + colx,
                               yaxis=dict(title=coly + ' of ' + colz),
                               xaxis=dict(title=colx))

        elif (viz == 'pareto'):
            print(
                '{}: {:0.1%} null ({:d} out of {:d})'\
                    .format(
                        colx
                        , source[colx].isnull().sum() / source.shape[0]
                        , source[colx].isnull().sum()
                        , source.shape[0]
                    )
                )
            print(
                '{}: {:0.1%} null ({:d} out of {:d})'\
                    .format(
                        colz
                        , source[colz].isnull().sum() / source.shape[0]
                        , source[colz].isnull().sum()
                        , source.shape[0]
                    )
                )
            sort_order = (asc == 'Ascending')
            temp = source
            if na:
                temp = temp.fillna(-1000)
            grouped = temp.groupby(colx)

            if (coly in ['count', 'sum', 'mean', 'std', 'max', 'min']):
                grouped = grouped.agg({colz: [coly]})
            elif (coly == 'uniques'):
                grouped = grouped.apply(lambda g: pd.Series(
                    g[colz].unique().size,
                    index=pd.MultiIndex.from_product([[colz], [coly]])))



            grouped = grouped.reset_index().sort_values([(colz, coly)], ascending=sort_order).head(colw)\
                .sort_values([(colz, coly)], ascending = (not sort_order))

            #             print(grouped)

            trace = go.Bar(y=grouped[colx],
                           x=grouped[colz][coly],
                           name=colx,
                           marker=dict(color='rgb(49,130,189)'),
                           orientation='h')
            layout = go.Layout(
                title=coly + ' of ' + colz + ' by ' + colx,
                yaxis=dict(
                    title=colx,
                    type="category",
                    #                     categoryorder = "category descending"
                    tickformat=".3f"),
                xaxis=dict(title=coly + ' of ' + colz),
                margin=dict(l=160))

        else:
            print(
                '{}: {:0.1%} null ({:d} out of {:d})'\
                    .format(
                        colx
                        , source[colx].isnull().sum() / source.shape[0]
                        , source[colx].isnull().sum()
                        , source.shape[0]
                    )
                )
            temp = source
            if na:
                temp = temp.fillna(-1000)
            trace = go.Histogram(x=temp[colx],
                                 name=colx,
                                 marker=dict(color='rgb(49,130,189)'))
            layout = go.Layout(title='distribution',
                               yaxis=dict(title='count'),
                               xaxis=dict(title=colx))

        data = [trace]
        fig = go.Figure(data=data, layout=layout)
        plot_url = py.iplot(fig)
Ejemplo n.º 21
0
import pandas as pd
import plotly.offline as pyo
import plotly.graph_objs as go
# Load CSV file from Datasets folder
df = pd.read_csv('../Datasets/Olympic2016Rio.csv')

# Sorting values and select 20 first value
new_df = df.sort_values(by=['Total'],
ascending = [False]).head(20).reset_index()
# Preparing data
# Create bars for each country, one for deaths, recoveries, and deaths the stack bars based on data per country
trace1 = go.Bar(x=new_df['NOC'], y=new_df['Bronze'], name='Bronze Medal',
marker = {'color': '#CD7F32'})
trace2 = go.Bar(x=new_df['NOC'], y=new_df['Silver'], name='Silver Medal',
marker = {'color': '#9EA0A1'})
trace3 = go.Bar(x=new_df['NOC'], y=new_df['Gold'], name='Gold Medal',
marker = {'color': '#FFD700'})
data = [trace1, trace2, trace3]
# Preparing layout
layout = go.Layout(title='Olympic Medal Earn By Countries during Rio Olympics 2016', xaxis_title= "Country" ,
yaxis_title = "Number Medals", barmode='stack')
# Plot the figure and saving in a html file
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename='Olympicstackbarchart.html')
def build_fig(df):
    
    # mini = int(min(data) - 5)
    # maxi = int(max(data) + 5)
    
    # print(mini, maxi)
    
    df = df.round(2)
    
    remaining = df['Total Interest']
    principal = df['Principal']
    interest = df['Balance']
    
    remaining_trace = go.Scatter(x=df['Month'], y=remaining,
            mode='lines',
            name='Remaining',
            line = {'color':colours['remaining'], 'shape': 'spline', 'smoothing': 1},
            fill='tozeroy'
            )

    principal_trace = go.Scatter(x=df['Month'], y=principal, 
            mode='lines',
            name='Principal',
            line = {'color': colours['principal'], 'shape': 'spline', 'smoothing': 1},
            fill='tozeroy',
            )
    
    interest_trace = go.Scatter(x=df['Month'], y=interest, 
            mode='lines',
            name='Interest',
            line = {'color': colours['interest'], 'shape': 'spline', 'smoothing': 1},
            fill='tozeroy',
            )
    
    data = [interest_trace, principal_trace, remaining_trace]
    
    layout = go.Layout(paper_bgcolor='rgba(0,0,0,0)',
               plot_bgcolor='rgba(0,0,0,0)',
                font={
                      #'family': 'Courier New, monospace',
                      #'size': 18,
                      'color': 'grey'
                      },
                xaxis={    
                    #'showgrid': False, # thin lines in the background
                    'zeroline': False, # thick line at x=0
                    #'visible': False,  # numbers below
                    #'tickmode':'linear',
                    #'autorange':False,
                    'gridcolor':'#393939'
                },                                                
                yaxis={
                    #'showgrid': False,
                    'zeroline': False,
                    'visible': False,
                },
                autosize=False,
                margin=dict(
                      l=0,
                      r=0,
                      b=2,
                      t=0,
                ),
            )

    fig = go.Figure(data=data, layout=layout)
    
    fig.update_layout(
        height=400,
        #width=300,
        hovermode='x',
        showlegend=False,
    )
    
    return fig
Ejemplo n.º 23
0
def plot_cities_map(provstates, cities, date_range, country):
    country = '' or country
    df = terrorism[(terrorism['provstate'].isin(provstates)
                    | terrorism['city'].isin(cities))
                   & (terrorism['country_txt'] == country)
                   & terrorism['date'].between(mydates[date_range[0]],
                                               mydates[date_range[1]])]

    return {
        'data': [
            go.Scattergeo(
                lon=[
                    x + random.gauss(0.04, 0.03)
                    for x in df[df['provstate'] == c]['longitude']
                ],
                lat=[
                    x + random.gauss(0.04, 0.03)
                    for x in df[df['provstate'] == c]['latitude']
                ],
                name=c,
                hoverinfo='text',
                opacity=0.9,
                marker={
                    'size': 9,
                    'line': {
                        'width': .2,
                        'color': '#cccccc'
                    }
                },
                hovertext=df[df['provstate'] == c]['city'].astype(str) + ', ' +
                df[df['provstate'] == c]['country_txt'].astype(str) + '<br>' +
                [
                    datetime.datetime.strftime(d, '%d %b, %Y')
                    for d in df[df['provstate'] == c]['date']
                ] + '<br>' + 'Perpetrator: ' +
                df[df['provstate'] == c]['gname'].astype(str) + '<br>' +
                'Target: ' + df[df['provstate'] == c]['target1'].astype(str) +
                '<br>' + 'Deaths: ' +
                df[df['provstate'] == c]['nkill'].astype(str) + '<br>' +
                'Injured: ' + df[df['provstate'] == c]['nwound'].astype(str) +
                '<br><br>' + [
                    '<br>'.join(textwrap.wrap(x, 40))
                    if not isinstance(x, float) else ''
                    for x in df[df['provstate'] == c]['summary']
                ]) for c in provstates
        ] + [
            go.Scattergeo(
                lon=[
                    x + random.gauss(0.04, 0.03)
                    for x in df[df['city'] == c]['longitude']
                ],
                lat=[
                    x + random.gauss(0.04, 0.03)
                    for x in df[df['city'] == c]['latitude']
                ],
                name=c,
                hoverinfo='text',
                opacity=0.9,
                marker={
                    'size': 9,
                    'line': {
                        'width': .2,
                        'color': '#cccccc'
                    }
                },
                hovertext=df[df['city'] == c]['city'].astype(str) + ', ' +
                df[df['city'] == c]['country_txt'].astype(str) + '<br>' + [
                    datetime.datetime.strftime(d, '%d %b, %Y')
                    for d in df[df['city'] == c]['date']
                ] + '<br>' + 'Perpetrator: ' +
                df[df['city'] == c]['gname'].astype(str) + '<br>' + 'Target: '
                + df[df['city'] == c]['target1'].astype(str) + '<br>' +
                'Deaths: ' + df[df['city'] == c]['nkill'].astype(str) +
                '<br>' + 'Injured: ' +
                df[df['city'] == c]['nwound'].astype(str) + '<br><br>' + [
                    '<br>'.join(textwrap.wrap(x, 40))
                    if not isinstance(x, float) else ''
                    for x in df[df['city'] == c]['summary']
                ]) for c in cities
        ],
        'layout':
        go.Layout(
            title='Terrorist Attacks in ' + country + '  ' +
            datetime.datetime.strftime(mydates[date_range[0]], '%b, %Y') +
            ' - ' +
            datetime.datetime.strftime(mydates[date_range[1]], '%b, %Y') +
            '<br>' + ', '.join(list(provstates)) + ' ' +
            ', '.join(list(cities)),
            font={'family': 'Palatino'},
            titlefont={'size': 22},
            paper_bgcolor='#eeeeee',
            plot_bgcolor='#eeeeee',
            width=1420,
            height=650,
            annotations=[{
                'text': '<a href=">UNC Data Analytics Boot Camp</a>',
                'x': .2,
                'y': -.1,
                'showarrow': False
            }, {
                'text': 'Data: START Consortium',
                'x': .2,
                'y': -.13,
                'showarrow': False
            }],
            geo={
                'showland': True,
                'landcolor': '#eeeeee',
                'countrycolor': '#cccccc',
                'showsubunits': True,
                'subunitcolor': '#cccccc',
                'subunitwidth': 5,
                'showcountries': True,
                'oceancolor': '#eeeeee',
                'showocean': True,
                'showcoastlines': True,
                'showframe': False,
                'coastlinecolor': '#cccccc',
                'lonaxis': {
                    'range':
                    [df['longitude'].min() - 1, df['longitude'].max() + 1]
                },
                'lataxis': {
                    'range':
                    [df['latitude'].min() - 1, df['latitude'].max() + 1]
                }
            })
    }
Ejemplo n.º 24
0
import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as pd
# Load CSV file from Datasets folder
df = pd.read_csv('../Datasets/Weather2014-15.csv')
# Preparing data
data = [go.Heatmap(x=df['day'],
y=df['month'],
z=df['record_max_temp'].values.tolist(),
colorscale='Jet')]
# Preparing layout sepreate data into calendar layout with color intesties as the amount of casses
layout = go.Layout(title='Average Max Temperature', xaxis_title="Day of Week",
yaxis_title="Week of Month")
# Plot the figure and saving in a html file
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename='weatherheatmap.html')
Ejemplo n.º 25
0
# Perform imports here:
import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objs as go
import pandas as pd

# Launch the application:
app = dash.Dash()

# Create a DataFrame from the .csv file:
df = pd.read_csv('data/OldFaithful.csv')

scatter = dcc.Graph(
    id='Old Faithful',
    figure={
        'data': [go.Scatter(x=df['X'], y=df['Y'], mode='markers')],
        'layout':
        go.Layout(title='Old Faithful Eruption Intervals v Durations',
                  xaxis={'title': 'Duration of eruption (minutes)'},
                  yaxis={'title': 'Interval to next eruption'})
    })

# Create a Dash layout that contains a Graph component:

app.layout = html.Div([scatter])

# Add the server clause:
if __name__ == '__main__':
    app.run_server()
def update_graph(hotel_group_id, hotel_id, hotel__city, start_date, end_date, **kwargs):
    
    # get metadata for current user
    current_user = kwargs['user']
    user_id = current_user.pk
    user_metadata = UserMetadata.objects.get(user_id=user_id)

    hotel_group_filter = {} if hotel_group_id == None else {"service__hotel_group_id": hotel_group_id}
    hotel_filter = {} if hotel_id == None else {"service__hotel_id": hotel_id}
    hotel__city_filter = {} if hotel__city == None else {"service__hotel__city": hotel__city}
    servicebooking_start_date_filter = {} if start_date == None else {"start_date_time__gte": dt.strptime(start_date.split(' ')[0], '%Y-%m-%d')}
    servicebooking_end_date_filter = {} if end_date == None else {"end_date_time__lte": dt.strptime(end_date.split(' ')[0], '%Y-%m-%d')}

    # if group or hotel then apply filter
    if current_user.groups.filter(name='Hotel Group Administrators').exists(): 
        hotel_group_id = user_metadata.hotel_group_id
        # bookings = Booking.objects.filter(hotel_group_id=hotel_group_id)
        services = ServiceBooking.objects.filter(service__service_type='co_share').filter(hotel_group_id=hotel_group_id)\
                    .filter(**hotel__city_filter).filter(**hotel_filter).filter(**servicebooking_start_date_filter)\
                    .filter(**servicebooking_end_date_filter)\
                    .values('service__hotel_id', 'service__hotel__hotel_name')\
                    .annotate(total=Count('service__hotel_id'))
    elif current_user.groups.filter(name='Hotel Administrators').exists(): 
        hotel_id = user_metadata.hotel_id
        services = ServiceBooking.objects.filter(hotel_id=hotel_id).filter(service__service_type='co_share')\
                    .filter(**servicebooking_start_date_filter).filter(**servicebooking_end_date_filter)\
                    .values('service__hotel_id', 'service__hotel__hotel_name')\
                    .annotate(total=Count('service__hotel_id'))
    else:
        services = ServiceBooking.objects.filter(**hotel_group_filter).filter(service__service_type='co_share')\
                    .filter(**hotel__city_filter).filter(**hotel_filter).filter(**servicebooking_start_date_filter)\
                    .filter(**servicebooking_end_date_filter)\
                    .values('service__hotel_id', 'service__hotel__hotel_name')\
                    .annotate(total=Count('service__hotel_id'))             

    if len(services) == 0:
        return {
            "data": [go.Pie(labels=[], values=[], textinfo='label')],
            "layout": go.Layout({
                "annotations": [
                    {
                        "text": "No matching data found",
                        "showarrow": False
                    }
                ]
            })
        }         
    else: 
        values=[booking['total'] for booking in list(services)]
        labels=[booking['service__hotel__hotel_name'] for booking in list(services)]

        return {
            "data": [go.Pie(labels=labels, values=values, textinfo='none')],
            "layout": go.Layout(
                margin=dict(
                    l=50,
                    r=50,
                    b=0,
                    t=50,
                    pad=0
                ),  
                autosize=True,      
                width=350,
                legend=dict(
                    y=1.1,
                    orientation='h',
                ),  
                colorway=['#2e3164','#e5e7fe','#c3c7ca']
            )
        } 
Ejemplo n.º 27
0
             method='update',
             args=get_color_set(4)),
    ]),
         direction='left',
         pad={
             'r': 10,
             't': 10
         },
         showactive=False,
         type='buttons',
         x=0.1,
         xanchor='left',
         y=1.1,
         yanchor='top')
])
layout = go.Layout()
layout = dict(
    hovermode='closest',
    #               hoverlabel_align = 'right',
    hoverlabel_font_size=10,
    yaxis=dict(zeroline=False, showgrid=False, showticklabels=False),
    xaxis=dict(zeroline=False, showgrid=False, showticklabels=False),
    template='plotly_dark',
    paper_bgcolor='#0d112b',
    plot_bgcolor='#0d112b',
    updatemenus=updatemenus,
)
fig = go.Figure(data=data, layout=layout)
# file = plot(fig, filename='Sentence_encode.html')
#=====================================================================
import dash
Ejemplo n.º 28
0
tmp = dept_37_27_df.groupby("MonthDate").agg({
    "INCIDENT_REASON": "count"
}).reset_index()
tmp

import plotly.plotly as py
import plotly.graph_objs as go

trace1 = go.Scatter(x=tmp["MonthDate"],
                    y=tmp.INCIDENT_REASON,
                    name="Month wise Incidents")
# trace2 = go.Scatter(x=tmp["MonthDate"], y=tmp.INCIDENT_REASON)

data = [trace1]
layout = go.Layout(height=400, title="Incidents in Austin Texas")
fig = go.Figure(data, layout)
iplot(fig)

# In[ ]:

a = dept_37_27_df["SUBJECT_GENDER"].value_counts()
tr1 = go.Bar(x=a.index, y=a.values, name="Gender")

a = dept_37_27_df["INCIDENT_REASON"].value_counts()
tr2 = go.Bar(x=a.index, y=a.values, name="INCIDENT_REASON")

a = dept_37_27_df["SUBJECT_RACE"].value_counts()
tr3 = go.Bar(x=a.index, y=a.values, name="SUBJECT_RACE")

fig = tools.make_subplots(
Ejemplo n.º 29
0
import pandas as pd
import plotly.offline as pyo
import plotly.graph_objs as go
df = pd.read_csv('../Datasets/CoronavirusTotal.csv')
# Removing empty spaces from State column to avoid errors
df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
# Creating unrecovered column
df['Unrecovered'] = df['Confirmed'] - df['Deaths'] - df['Recovered']
# Removing China and Others from data frame
df = df[(df['Country'] != 'China') & (df['Country'] != 'Others')]
# Creating sum of number of cases group by Country Column
new_df = df.groupby(['Country']).agg({'Confirmed': 'sum', 'Recovered': 'sum', 'Unrecovered': 'sum'}).reset_index()
# Preparing data
data = [go.Scatter(x=new_df['Recovered'],
y=new_df['Unrecovered'],
text=new_df['Country'],
mode='markers',
marker=dict(size=new_df['Confirmed'] /100,color=new_df['Confirmed'] / 100, showscale=True))
]
# Preparing layout
layout = go.Layout(title='Corona Virus Confirmed Cases', xaxis_title="Recovered Cases",
yaxis_title="Unrecovered Cases", hovermode='closest')
# Plot the figure and saving in a html file
fig = go.Figure(data=data, layout=layout)
pyo.plot(fig, filename='coronabubblechart.html')
Ejemplo n.º 30
0
    f'nWW New deaths last-5 records:\n\n {cv19_countries_day_new_deaths.tail(5)}'
)
"""# Draw a chart with daily New (WW) Confirmed Cases and"""

data = [
    go.Scatter(name="WW New Confirmed cases",
               x=cv19_countries_day_new_confirmed_cases['dateRep'],
               y=cv19_countries_day_new_confirmed_cases['cases']),
    go.Scatter(name="WW New deaths",
               x=cv19_countries_day_new_deaths['dateRep'],
               y=cv19_countries_day_new_deaths['deaths']),
]

# plot titles and axis labels
layout = go.Layout(title=f'Worldwide New Confirmed cases and deaths',
                   xaxis=dict(title='Date'),
                   yaxis=dict(title='New Confirmed cases/New deaths'))

# plot the Figure object using the 'iplot' method
fig = go.Figure(data=data, layout=layout)
iplot(fig)
"""# ACTION : Choose the countries you want to compare or update the list of countries you want to study (Multi-selection with CTRL key)"""

countries_widget = widgets.SelectMultiple(
    options=df['countriesAndTerritories'].unique().tolist(),
    value=countries,
    rows=10,
    description='countriesAndTerritories',
    disabled=False)

try: