Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save AsselKashkenbayeva/8e5ac329c9cf7d425470b4489ef47f61 to your computer and use it in GitHub Desktop.

Select an option

Save AsselKashkenbayeva/8e5ac329c9cf7d425470b4489ef47f61 to your computer and use it in GitHub Desktop.
simple demonstrating of interactive bar plot with duel axis using plotly dash.
#app required libraries
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
#libraries required for visualisation
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
#general
import pandas as pd
import numpy as np
import random
from datetime import datetime, timedelta
#create dummy data
car_inventory = pd.DataFrame({'Car Brand': random.choices(['Tesla', 'Tayota', 'Kia', 'Honda', 'Volvo', 'Skoda'], k = 1000)})
car_inventory['Fuel Type'] = random.choices(['Electric', 'Diesal', 'Hybrid', 'Petrol'], k = len(car_inventory))
car_inventory['Color'] = random.choices(['White', 'Blue', 'Silver', 'Black'], k = len(car_inventory))
#our fictional car dealership deals mainly with new cars, so lets assign weights to this attribute where the probability of a car within the inventory being new is 0.8
car_inventory['New/Used'] = np.random.choice(['New', 'Used'],len(car_inventory), p = [0.8,0.2])
car_inventory['Cost'] = random.sample(range(100, 15000), len(car_inventory))
#pick random date from last 90 days for car purchase
def random_date():
start = datetime.now()
end = start + timedelta(days=90)
random_date = start + (end - start) * random.random()
return random_date
car_inventory['Purchase Date'] = car_inventory['Cost'].apply(lambda x: random_date().strftime('%Y/%m/%d'))
def remove_cost():
no_cost = list(car_inventory.columns)
no_cost.remove('Cost')
return no_cost
app = Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(id='car_attribute_dropdown',
placeholder='Car Attribute',options= [{'label': i, 'value': i} for i in remove_cost()],style= { 'width': '50%','text-align':'center',
'font-size' : 'large',
'font-weight' : 'bold',
'font-family' : "DejaVu Sans Mono, monospace"}),
dcc.Graph( id = 'bar_graph', style= { 'width': '80%', 'height': '800px'})])
@app.callback(
Output("bar_graph", "figure"),
Input("car_attribute_dropdown", "value"),
)
def make_grouped_plot(attribute):
#an if statement to handle if no value is selected in dropdown and None is passed
if attribute is None:
attribute = 'Car Brand'
df = pd.DataFrame(car_inventory.groupby(attribute)['Cost'].agg({'sum', 'size'}).reset_index()).rename(columns= {'size' : 'Unit', 'sum': 'Potential Revenue'})
#create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
#with plotly.go, each trace needs to be added into the figure seperately
fig.add_trace(go.Bar(x=df[attribute], y=df['Unit'], name='Unit Count' ,marker_color = '#43B02A',offsetgroup=1 ,), secondary_y=False)
fig.add_trace(go.Bar(x=df[attribute], y=df['Potential Revenue'], name='Potential Revenue' ,marker_color = '#00A3E0',offsetgroup=2 ,hovertemplate = '%{y:$,.0f}'), secondary_y=True)
#change layout preferences
fig.update_layout(
barmode='group',
font_size = 20,
hovermode="x unified",
)
#set y-axes titles
fig.update_yaxes(title_text="Potential Revenue: <b>Cost (in $) </b> ", secondary_y=True)
fig.update_yaxes(title_text="Unit <b>Count</b>", secondary_y=False)
return fig
if __name__ == '__main__':
#app.run_server(host='127.0.0.1', port= int(os.environ['CDSW_APP_PORT']))
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment