Skip to content

Instantly share code, notes, and snippets.

@AsselKashkenbayeva
Created March 18, 2022 19:04
Show Gist options
  • Save AsselKashkenbayeva/872527a5d42c73dbed889e797763839d to your computer and use it in GitHub Desktop.
Save AsselKashkenbayeva/872527a5d42c73dbed889e797763839d to your computer and use it in GitHub Desktop.
Gist to show to to create a duel axis bar plot using plotly.go
#import required libraries
import pandas as pd
import numpy as np
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
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(2000, 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'))
car_unit_cost_groupby = pd.DataFrame(car_inventory.groupby('Car Brand')['Cost'].agg({'sum', 'size'}).reset_index()).rename(columns= {'size' : 'Unit', 'sum': 'Potential Revenue'})
def make_grouped_plot(df, attribute):
#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 = 14,
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)
fig.show()
make_grouped_plot(car_unit_cost_groupby, 'Car Brand')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment