I have two charts I want to display side by side, a barchart and a piechart. and probably the same barchart below these 2 charts. I have tried a lot and I would really appreciate some help.
This is my code:
import numpy as np
import pandas as pd
from pandas import read_excel
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Output, Input, State
import plotly.figure_factory as ff
import plotly.io as pio
# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# app = dash.Dash()
external_stylesheets = ['https://codepen.io/amyoshino/pen/jzXypZ.css']
app = dash.Dash(__name__,external_stylesheets=external_stylesheets)
# app = dash.Dash()
file_name = 'samplePop1.csv'
df = pd.read_csv(file_name)
print(df.head())
colors = {
'BLACK' : '#000000',
'TEXT' : '#696969',
'PLOT_COLOR' : '#C0C0C0',
'WHITE' : '#FFFFFF',
'GOLD' : '#EEBC35' ,
'BROWN' : '#53354D' ,
'GREEN' : '#42CE90' ,
'RED' : '#F87861' ,
'YELLOW' : '#F1F145' ,
'SKY_BLUE' : '#A3DBE1' ,
'SILVER': '#CCCCCC' ,
'LIGHT_BLACK' : '#374649'
}
#status options for dropdown
status_options = []
for status in df['Status'].unique():
status_options.append({'label':str(status),'value':status})
# print(status_options)
#Pie chart static function
def pop_pie():
pie_data = df.groupby('Status')['Population Census 1991'].count()
pie_dataframe = pie_data.to_frame().reset_index()
# print(pie_dataframe)
# print(df['Status'].unique())
# print(pie_data.tolist())
# print(type(pie_data.tolist()))
# print(pie_data['Status'].tolist())
# print(pie_data['Population Census 1991'].tolist())
trace1 = go.Pie(
labels = pie_dataframe['Status'].tolist(),
values= pie_dataframe['Population Census 1991'].tolist(),
textinfo='label+percent',
name='population 1991 status wise',pull=[0,0,0,0,0,0,0,0,0]
)
data = [trace1]
layout = go.Layout(
title='piechart',
)
fig = go.Figure(data=data)
return fig
'''
#Barchart static function
def pop_bar():
trace1 =go.Bar(y=df['Population Census 1991'],
x=df['Name'],name ='1991',
marker = {'color' : colors['GREEN']}
# orientation='h'
)
trace2 =go.Bar(y=df['Population Census 2001'],
x=df['Name'],name ='2001',
marker = {'color' : colors['RED']}
# orientation='h'
)
trace3 = go.Bar(y=df['Population Census 2011'],
x=df['Name'],name ='2011',
marker = {'color' : colors['YELLOW']}
# orientation='h'
)
data = [trace1, trace2, trace3]
#layout = go.Layout(barmode='group', xaxis={'categoryorder':'array', 'categoryarray':df['District']})
# layout = go.Layout(barmode='group', xaxis={'categoryorder':'total descending'})
layout = go.Layout(
title='Population Census',
paper_bgcolor=colors['LIGHT_BLACK'],
plot_bgcolor=colors['LIGHT_BLACK'],
font ={'color' : colors['WHITE']},
xaxis_tickfont_size=14,
yaxis=dict(showgrid=False,
title='Population',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=0,
y=1.0,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)',
orientation="h"
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1, # gap between bars of the same location coordinate.
xaxis={'categoryorder':'total descending'})
fig = go.Figure(data=data, layout=layout)
return fig
'''
app.layout = html.Div(children=[
html.Div(
[
html.H1("Test Dashboard",
style = {
'textAlign' : 'center',
'color' : colors['SILVER']
}
),
html.Div('Developed by Centroxy Solution pvt.ltd',
style = {
'textAlign' : 'right',
'color' : colors['SILVER']
}
),
html.Img(
src="https://i.imgur.com/CIxE22f.png",
className='three columns',
style={
'height': '9%',
'width': '9%',
'float': 'right',
'position': 'relative',
'margin-top': '-91px',
}),
html.Br(),
html.Br()
],style={'backgroundColor': colors['LIGHT_BLACK']}
),
html.Div(
dcc.Dropdown(id='status_picker',options=status_options,
placeholder="Select Status",
style = {'color' : colors['LIGHT_BLACK']},
multi=True,
clearable=True,
searchable=True
)
#,style={"background-color": colors['LIGHT_BLACK']}
,style={'backgroundColor': colors['LIGHT_BLACK']}
),
html.Div([
dcc.Graph(id='Bar-Chart')
]),
html.Div([
dcc.Graph(id='pie-chart', figure=pop_pie())
]),
])
#app.callback(Output('Bar-Chart','figure'),
[Input('status_picker','value')])
def update_figure(selected_status):
print(selected_status)
if selected_status == [] or selected_status == None:
trace1 =go.Bar(y=df['Population Census 1991'],
x=df['Name'],name ='1991',
marker = {'color' : colors['GREEN']}
# orientation='h'
)
trace2 =go.Bar(y=df['Population Census 2001'],
x=df['Name'],name ='2001',
marker = {'color' : colors['RED']}
# orientation='h'
)
trace3 = go.Bar(y=df['Population Census 2011'],
x=df['Name'],name ='2011',
marker = {'color' : colors['YELLOW']}
# orientation='h'
)
else:
filtered_df = df[df['Status'].isin(selected_status)]
print(filtered_df)
trace1=go.Bar(y=filtered_df['Population Census 1991'],
x=filtered_df['Name'],name ='1991',
marker = {'color' : colors['GREEN']}
# orientation='h'
)
trace2=go.Bar(y=filtered_df['Population Census 2001'],
x=filtered_df['Name'],name ='2001',
marker = {'color' : colors['RED']}
# orientation='h'
)
trace3=go.Bar(y=filtered_df['Population Census 2011'],
x=filtered_df['Name'],name ='2011',
marker = {'color' : colors['YELLOW']}
# orientation='h'
)
traces= [trace1,trace2,trace3]
'''
for status in filtered_df['Status'].unique():
df_by_status = filtered_df[filtered_df['Status'] == selected_status]
traces.append(
go.Bar(y=df_by_status['Population Census 1991'],
x=df_by_status['Name'],name ='1991',
marker = {'color' : colors['GREEN']}
# orientation='h'
))
traces.append(
go.Bar(y=df_by_status['Population Census 2001'],
x=df_by_status['Name'],name ='2001',
marker = {'color' : colors['RED']}
# orientation='h'
))
traces.append(go.Bar(y=df_by_status['Population Census 2011'],
x=df_by_status['Name'],name ='2011',
marker = {'color' : colors['YELLOW']}
# orientation='h'
))'''
return {
'data' : traces,
'layout' : go.Layout(
title='Population Census',
paper_bgcolor=colors['LIGHT_BLACK'],
plot_bgcolor=colors['LIGHT_BLACK'],
font ={'color' : colors['WHITE']},
xaxis_tickfont_size=14,
yaxis=dict(showgrid=False,
title='Population',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=0,
y=1.0,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)',
orientation="h"
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1, # gap between bars of the same location coordinate.
xaxis={'categoryorder':'total descending'})
}
if __name__ == '__main__':
app.run_server(port = '8080' , debug ='True')
Also the background colour is not completely the one i specified , please help
Attaching an image below
you need to use row and columns className to html.Div elements (example here). Alternatively you can use bootstrap elements.
In your case it would be something like:
app.layout = html.Div([
html.Div(
className="row",
children=[
html.Div(
className="six columns",
children=[
html.Div(
children=dcc.Graph(id='left-top-bar-graph')
)
]
),
html.Div(
className="six columns",
children=html.Div(
children=dcc.Graph(id='right-top-pie-graph'),
)
)
]
),
html.Div(
className="row",
children=[
html.Div(
className="twelve columns",
children=[
html.Div(
children=dcc.Graph(id='bottom-bar-graph')
)
]
)
]
)
])
Related
I would like to display/use/put my LDA model in my dash app. Here's the code for the LDA model which works and that I've saved in html on my computer :
# Libraries
import spacy
from gensim.corpora import Dictionary
from gensim.models import LdaModel
import pyLDAvis.gensim_models
import pandas as pd
nlp_teletravail = spacy.load("fr_core_news_sm")
# Create df for the example
data = [['tweet content in french'], ['tweet 2 content in french'], ['tweet 3 content in french']] # lots of tweets and other columns but not useful for the example
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Preprocessed_tweets'])
spacy_docs_teletravail = list(nlp_teletravail.pipe(df["Preprocessed_tweets"]))
# Create empty list called docs_teletravail
docs_teletravail = []
# Pre processing
# For each document in spacy_docs_teletravail
for doc in spacy_docs_teletravail:
# We create empty list called tokens_teletravail
tokens_teletravail = []
# for each token in each document of spacy_docs_teletravail
for token in doc:
# pre processing 1 and 2
if len(token.orth_) > 2 and not token.is_stop:
# pre processing 3 and 4
tokens_teletravail.append( token.lemma_.lower() )
# append results of tokens_teletravail in docs_teletravail
docs_teletravail.append( tokens_teletravail )
dictionary_teletravail = Dictionary(docs_teletravail)
corpus_teletravail = [ dictionary_teletravail.doc2bow(doc) for doc in docs_teletravail]
model_teletravail_passes_5 = LdaModel(corpus=corpus_teletravail,
id2word=dictionary_teletravail,
num_topics=10,
chunksize=1000,
passes=5,
random_state=1)
vis_data_teletravail = pyLDAvis.gensim_models.prepare(model_teletravail_passes_5, corpus_teletravail, dictionary_teletravail, sort_topics=False)
# Export the graph and store it where we want in our computer
pyLDAvis.save_html(vis_data_teletravail, 'C:/Users/mario/Downloads/lda_model_passes_5.html')
Maybe you can add content for the tweets (random sentences that you can find on the internet). I think I can't load my html file on the post but don't hesitate to tell me if it's possible and I'll do it so that you don't have to run the first part. And here's the code of my dash app where I have multiple tabs and subtabs but I don't put their content here because it's useless, you just have the code with the tabs (empty). I would like to put the LDA model in tab 3 (Latent Dirichlet Allocation Model) subtab 10 (LDA Model 10 topics). I left most of my attempts in comments to return the LDA model in subtab10 but nothing is happening (no errors, nothing appearing on the dash app). Thank you for your help !
# Needed libraries
#import pandas as pd
import dash
import dash_bootstrap_components as dbc
#import plotly.express as px
#import numpy as np
from dash import dcc, html
from dash.dependencies import Input, Output
from dash_bootstrap_templates import ThemeSwitchAIO, template_from_url
# Two different templates stored in variables for the dash app
template_theme1 = "cyborg"
template_theme2 = "lumen"
url_theme1 = dbc.themes.CYBORG
url_theme2 = dbc.themes.LUMEN
# Link which gives access to the templates
dbc_css = (
"https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates#V1.0.1/dbc.min.css"
)
# Create the app and define the main theme in external_stylesheets
app = dash.Dash(__name__, external_stylesheets=[url_theme1, dbc_css])
# Define a sentence that appears on the top left of the app in order to choose between the two proposed themes
header = html.P("Click if you want to change theme of graphics",style={'textAlign': 'left','font-size':'300','font-family':'helvetica'})
# Create the layout of the app
app.layout = html.Div([ # html Div to use html components (style, text, tabs, subtabs etc)
html.H1('Health consequences during covid-19 pandemic dashboard', style={'textAlign': 'center','font-size':'300','font-family':'helvetica'}),
dbc.Container( # dbc container and row to use dbc Col to define the different themes to choose
dbc.Row(
[
dbc.Col( # Define the two possible themes to choose
[
header, # header is the sentence that we've dehttps://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-htmlfined earlier in header variable
ThemeSwitchAIO( # switch with icons
aio_id="theme", # id of the switch
themes=[url_theme1,url_theme2], # proposed themes that we've defined earlier
),
])])),
dcc.Tabs(id='tabs', value='Tab1', style={'background-color': 'black'}, children=[
# Create tabs and their sub tabs
dcc.Tab(label='Data information', id='tab1', value='Tab1', style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'},children =[ # First tab
dcc.Tabs(id="subtabs1", value='Subtab1',children=[ # Create sub tabs in the first tab
dcc.Tab(label='Basic information about the dashboard', id='subtab1', value='Subtab1',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 1
dcc.Tab(label='Number of collected tweets', id='subtab2', value='Subtab2',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 1
dcc.Tab(label='Number of collected tweets per month each year', id='subtab3', value='Subtab3',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 1
dcc.Tab(label='Wordcloud', id='subtab4', value='Subtab4',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 1
]),
dcc.Tab(label='Sentiment Analysis', id='tab2', value='Tab2',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Second tab
dcc.Tabs(id="subtabs2", value='Subtab2', children=[ # Create sub tabs for the second tab
dcc.Tab(label='Number or percentage of tweets according to sentiments', id='subtab5', value='Subtab5', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 2
dcc.Tab(label='Percentage of tweets according to sentiments and time slots', id='subtab6', value='Subtab6', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 2
dcc.Tab(label='Number or percentage of tweets according to sentiments and time slots', id='subtab7', value='Subtab7', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 2
dcc.Tab(label='Number or percentage of tweets according to sentiments each year', id='subtab8', value='Subtab8', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 2
]),
dcc.Tab(label='Latent Dirichlet Allocation Model', id='tab3', value='Tab3',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Third tab
dcc.Tabs(id="subtabs3", value='Subtab3', children=[
dcc.Tab(label='LDA Model interpretation', id='subtab9', value='Subtab9', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 3
dcc.Tab(label='LDA Model 10 topics', id='subtab10', value='Subtab10', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 3
dcc.Tab(label='LDA Model 5 topics', id='subtab11', value='Subtab11', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 3
]),
dcc.Tab(label='Network Graph', id='tab4', value='Tab4',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the fourth tab
dcc.Tabs(id="subtabs4", value='Subtab4', children=[
dcc.Tab(label='To determine', id='subtab13', value='Subtab13', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 4
dcc.Tab(label='To determine', id='subtab14', value='Subtab14', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 4
dcc.Tab(label='To determine', id='subtab15', value='Subtab15', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 4
])
])
])
############################################ Tab 3 LDA MODEL
############### Sub tab 10 LDA Model 10 topics
# Callback for Tab 3 and subtab 10 LDA Model 10 topics
#app.callback(Output('subtab10', 'children'), # Output
[Input('subtabs3', 'value'), # Input
Input(ThemeSwitchAIO.ids.switch("theme"),"value")]) # Another input is the selected theme/template
# Create function to display lda model
def display_lda_subtab10(value,toggle): # 2 parameters value for which subtab and toggle for theme/template
if value == 'Subtab10':# If we are in subtab2 in tab 1 we return a graph
template = template_theme1 if toggle else template_theme2 # We define the theme selected
#lda_10_topics = html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
#return html.Div([dcc.Graph(figure=lda_10_topics)])
# https://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-html
#return html.Div([dcc.Graph(id='example'),
# html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
# ])
#return html.Div([dcc.Graph(id='example'),
# html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
# ])
#https://stackoverflow.com/questions/68269257/local-html-file-wont-load-properly-into-dash-application
#return html.Div([html.Iframe(src="assets/lda_model_topics_10.html")])
# https://stackoverflow.com/questions/74534261/dash-include-custom-html-object
#lda_10_topics = html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
#with open("C:/Users/mario/Downloads/lda_model_passes_5_json.json",'r') as f:
#with open(lda_passes_5_json,'r') as f:
# return html.Div([dcc.Graph(figure=json.load(f))])
#return json.load(f)
#html.Iframe(src=r'static/lda_model_topics_10.html')
#html.Div([html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')])
# Run the dash app
if __name__ =='__main__':
app.run_server(debug=False)
I found the solution by creating a folder called assets on my computer. Then we put the lda.html file inside. After that you can add the following code in the function and it works (your python path should be the one where the folder 'assets" is) !
return html.Div([html.Iframe(src="assets/lda_model_topics_10.html")])
You might have to adjust height and width after : src="...", height=..., width=...
I am trying to define a callback function that is called when a cell of my pivot table is called.
My code is below.
Unfortunately test_function test function is only called once and not each time a cell is clicked as i want.
Is this possible and what changes do i need to make to achieve this?
import jupyter_dash as dash
from dash import html, Input, Output, State
import dash_pivottable
app = dash.JupyterDash(__name__)
server = app.server
app.layout = html.Div(
[dash_pivottable.PivotTable(
id='table',
data=[
['Animal', 'Count', 'Location'],
['Zebra', 5, 'SF Zoo'],
['Tiger', 3, 'SF Zoo'],
['Zebra', 2, 'LA Zoo'],
['Tiger', 4, 'LA Zoo'],
],
cols=["Animal"],
rows=["Location"],
vals=["Count"],
),
html.Div(id='click-data', style={'whiteSpace': 'pre-wrap'})]
)
#app.callback(
Output('click-data', component_property="children"),
[Input('table','clickData'),
Input("table", "hoverData"),
Input("table", component_property="cols"),
Input("table", component_property="rows"),
Input("table", component_property="rowOrder"),
Input("table", component_property="colOrder"),
Input("table", component_property="aggregatorName"),
Input("table", component_property="rendererName")]
)
def test_function(clickData, hoverData, cols, rows, row_order, col_order, aggregator, renderer):
print("hello")
print(rows)
print(cols)
print(hoverData)
return clickData
if __name__ == "__main__":
app.run_server(mode='inline')
MDDataTable(
pos_hint={"center_x":0.5,"center_y":0.4},
size_hint=(0.9,0.5),
check=True,
rows_num = 7,
use_pagination = True,
column_data=[
("MVC", dp(30)),
("ID", dp(15))
],
row_data = [
("Bakers Basin", "300"),
("Bayonee", "150"),
("Camden","150"),
("Cardiff","5"),
("Delanco","3"),
("Eatontown","3"),
("Edison","3"),
("Flemington","3"),
("Freehold","3"),
("Lodi","3"),
("Newark","3"),
("North Bergen","3"),
("Oakland","3"),
("Paterson","3"),
("Rahway","3"),
("Randolph","3"),
("Rio Grande","3"),
("Salem","3"),
("South Plainfield","3"),
("Toms River","3"),
("Vineland","3"),
("Wayne","3"),
("West Deptford","3")
]
)
Need your help with this?
I am trying match list newtracks(name of songs in folder) with lists filezto and album from spreadsheet.
If the name of songs in folder match list filezto and have an album of Nasb copy it to folders list(ordfldrtosrt) and if not nasb album copy songs to list(ntsubfldrs).
For some reason when ran the if statement does not synch them up in order to print that they match and copy the files to the folders. I have tried different option but cannot make it work. Thanks in advance.
albm = ["NASB", "NASB", "NASB", "NASB", "NTSB", "NTSB", "NTSB", "NTSB"]
newtracks = [
"Track1.mp3",
"Track2.mp3",
"Track3.mp3",
"Track4.mp3",
"Track5.mp3",
"Track5.mp3",
]
filezto = [
"Track1.mp3",
"Track2.mp3",
"Track3.mp3",
"Track4.mp3",
"Track5.mp3",
"Track5.mp3",
]
ordfldrtosrt = ["1-GEN-GENE", "2 - EXO - Exos", "3 - LEV - Lev", "4 - NUM - Numb"]
ntsubfldrs = ["1-MAT-Matt", "2 - MRK - Mar", "3 - LUK - LI", "4 - JHN - Jo"]
for album in albm:
for newtracks, filezto, ordfldrtosrt, ntsubfldrs in (
(ntk, ft, otm, nts)
for ntk in newtracks
for ft in filezto
for otm in ordfldrtosrt
for nts in ntsubfldrs
):
if album == "Nasb" and newtracks == filezto:
print("Yes", newtracks, " files to", filezto)
# shutil.copy('C:\\Users\\mrdrj\\Desktop\\SJ\\NASB\\'+newtracks, 'D:\\Desktop\\pythonProject\\Nasb\\'+ ordfldrtosrt+'\\'+newtracks)
else:
print("No", newtracks, " files to", filezto)
# shutil.copy('C:\\Users\\mrdrj\\Desktop\\SJ\\NASB\\'+newtracks, 'D:\\Desktop\\pythonProject\\Nasb\\'+ ntsubfldrs +'\\'+newtracks)
From your last comment, I am guessing that you have have a list of (album, track) from your spreadsheet and you are trying to match that up with a list of tracks from one of the albums in folder:
folder = [
"Track1.mp3",
"Track2.mp3",
"Track3.mp3",
"Track4.mp3",
"Track5.mp3",
"Track5.mp3",
]
spreadsheet = [
( "NASB", "Track1.mp3" ),
( "NASB", "Track2.mp3" ),
( "NASB", "Track3.mp3" ),
( "NASB", "Track4.mp3" ),
( "NASB", "Track5.mp3" ),
( "NASB", "Track5.mp3" ),
( "NTSB", "Track1.mp3" ),
( "NTSB", "Track2.mp3" ),
( "NTSB", "Track3.mp3" ),
( "NTSB", "Track4.mp3" ),
( "NTSB", "Track5.mp3" ),
( "NTSB", "Track5.mp3" )
]
for album, track in spreadsheet:
if album == 'NASB' and track in folder:
print('%s %s' % ('Yes', track))
else:
print('%s %s' % ('No', track))
with gives you the output:
Yes Track1.mp3
Yes Track2.mp3
Yes Track3.mp3
Yes Track4.mp3
Yes Track5.mp3
Yes Track5.mp3
No Track1.mp3
No Track2.mp3
No Track3.mp3
No Track4.mp3
No Track5.mp3
No Track5.mp3
so i am trying to make a interactive dashboard using dash plotly in python using below data as example:
Date Traded Qty Deliverable Qty Delivery % LTP Open Interest
0 2020-12-18 29816205 5872798 19.70 268.15 73110000
1 2020-12-21 55160758 14528986 26.34 272.00 71454000
2 2020-12-22 51189571 10781372 21.06 253.85 71013000
3 2020-12-23 29056404 4792004 16.49 258.20 67350000
4 2020-12-24 28585509 6820426 23.86 263.75 68697000
It is saved as pandas dataframe and want to it be similar to below image:
Sorry for my shitty drawing.
In chart I want "Delivery %" to be show when hover over "Deliverable Qty"
I have no experience with Dash, but this page will help you do it. I suggest you look into it and try to write some code before asking questions. I'm in a jupyterlab environment, so I've implemented some live riley for it.
import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import io
import pandas as pd
data = '''
Date "Traded Qty" "Deliverable Qty" "Delivery %" LTP "Open Interest"
0 2020-12-18 29816205 5872798 19.70 268.15 73110000
1 2020-12-21 55160758 14528986 26.34 272.00 71454000
2 2020-12-22 51189571 10781372 21.06 253.85 71013000
3 2020-12-23 29056404 4792004 16.49 258.20 67350000
4 2020-12-24 28585509 6820426 23.86 263.75 68697000
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Bar(x=df['Date'], y=df['Traded Qty'], name='Traded Qty'))
fig.add_trace(go.Bar(x=df['Date'],
y=df['Deliverable Qty'],
name='Deliverable Qty',
hovertext=df['Delivery %'],
hovertemplate='<br>'.join([
'Deliverable Qty: %{y}',
'Delivery %: %{hovertext}'
])
))
fig.add_trace(go.Scatter(x=df['Date'], y=df['LTP'], mode='lines+markers', name='LTP'), secondary_y=True)
fig.add_trace(go.Scatter(x=df['Date'], y=df['Open Interest'], mode='lines+markers', name='Open Interest'))
fig.update_layout(xaxis=dict(type = "category"), barmode='stack', margin=dict(l=20, r=20, t=20, b=20))
fig.update_yaxes(range=[0,300], secondary_y=True)
# instance create
app = JupyterDash(__name__)
# app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.H3(children='Trade Chart'),
dcc.Graph(
id='example-graph',
figure=fig
)
])
if __name__ == '__main__':
# notebook on action
app.run_server(mode='inline')
# app.run_server(debug=True)