location dash bootstrap navbar - python

I have a navbar where i want the links in the center. I have them now on the right using classname 'ml-auto' but i cant' manage them to move to the center. Anyone who can help? Below my code.
nav_item = dbc.Nav(
[
dbc.NavItem(dbc.NavLink("World Map", active= True, href="/page-1")),
dbc.NavItem(dbc.NavLink("Table", active= True, href="/page-2")),
dbc.NavItem(dbc.NavLink("Moran's l", active= True, href="/page-3")),
dbc.NavItem(dbc.NavLink("Scatter Plots", active= True, href="/page-4"))
],
fill= True
)
navbar = dbc.Navbar(
[
html.A(
# Use row and col to control vertical alignment of logo / brand
dbc.Row(
[
dbc.Col(html.Img(src= oord_logo, height="100px"), className="ml-5"),
],
align="center",
no_gutters=True,
),
href="https://plot.ly",
),
dbc.NavbarToggler(id="navbar-toggler"),
dbc.Nav([nav_item], navbar=True, className="ml-auto",)
],
color="white",
dark=False,
className = "mb-5"
)

Use mr-auto instead of ml-auto.
With mr-auto you get margin on the right. This is what you want since you want the element with this class (the Nav component) displayed on the left.
Unrelated to the problem, but you nest one Nav component in another which seems unnecessary. Also you've put the NavbarToggler component in the middle which means the hamburger button generated by this component will also be displayed in the middle.

Related

Dash dcc Input, disabled attribute is doing the opposite of what i want it too

layout = html.Div([
html.H1("Registration"),
html.H4("Username: "),
dcc.Input(id="username"),
html.Div([
html.H3(option[0]),
html.Button("Yes", id="stock_y", n_clicks=0),
html.Button("No", id="stock_n", n_clicks=0),
html.Br(),
dcc.Input(id="stock", placeholder="Please enter stock here", disabled="True")
]),
])
#callback(
Output("stock", component_property="disabled"),
Input("stock_y", "n_clicks")
)
def enable(clicks):
if clicks > 0:
return "False"
I want the text box to be initially disabled and if user clicks the yes button than this will enable the text box. However when i open the page the text box is enabled and when i click the yes button it disables the text box. Why is this and how do i fix it?
example: https://imgur.com/a/BqLFNID
tried changing false and true statements and was expecting the box to be initially disabled and become enabled after clicking yes by swapping the disabled attribute from "True" to "False"
The values need to be booleans, not strings. So you should have:
dcc.Input(id="stock", placeholder="Please enter stock here", disabled=True)
And in the callback:
def enable(clicks):
if clicks > 0:
return False
return True # good to set a default, otherwise it will be set to None

duplicate callback outputs dash figure

How can I process when I have 2 callbacks functions with the same output (in that case : a graph) knowing that the first callback function returns a graph and a slider, whereas the input of 2nd callback function is the value of the new slider (created thanks to the first slider ) and returns also a graph (by adding new traces on the old traces)
The code is like that :
# Create Div to place a conditionally visible element inside
myslider = html.Div(
id='slider-container',
children=[
# Create a slider to hide/show
dcc.Slider(0,5,
step=1,
value=0,
id="newslider"
)
],
hidden=True,
)
mygraph = html.Div(dcc.Graph(id="graph", figure=go.Figure(go.Scattergeo())))
mydropdown = html.Div(dcc.Dropdown(['NYC', 'MTL', 'SF'], id="dropdown",
multi=True,
clearable=False))
layout = dbc.Container([mydropdown, mygraph, myslider,html.Div(id='slider-output-container',hidden=True)])
#app.callback(Output(component_id='graph', component_property='figure'),
Output(component_id='newslider', component_property='max'),
Output("newslider", "marks"),
Output(component_id='slider-container', component_property='hidden'),
Input(component_id='dropdown', component_property='value'),
Input(component_id='timeslider', component_property='value'),
State(component_id='newslider', component_property='max'),
State("newslider", "marks"),
prevent_initial_call=True
)
def create_graph_and_slider(dropdown,value,maxi,marks):
#created the initial traces of the graph associated to the newslider thanks to the value of dropdown
return fig, maxi, marks, False
#app.callback(Output(component_id='slider-output-container', component_property='children'),
Output(component_id='slider-output-container', component_property='hidden'),
Output(component_id='graph', component_property='figure'),
Input(component_id='newslider', component_property='value'),
prevent_initiall_call=True
)
def update_graph_from_extrapolation_slider(value):
#add new traces in the graph thanks to the value of new slider
return 'You have selected "{}"'.format(value), False, fig

How do I edit a cell in flet's DataTable?

Flet's DataTable has a show_edit_icon property, but I don't know how do something when the icon is pressed.
This is an example code:
import flet as ft
def main(page: ft.Page):
page.add(
ft.DataTable(
columns=[
ft.DataColumn(ft.Text("First name")),
ft.DataColumn(ft.Text("Last name")),
],
rows=[
ft.DataRow(
cells=[
ft.DataCell(ft.Text("John"), show_edit_icon=True),
ft.DataCell(ft.Text("Smith")),
],
),
],
),
)
ft.app(target=main, view=ft.WEB_BROWSER)
I see the edit icon, but how do I connect it to some function that receives the cell that is being edited?
As per the doccumentation, In FLET data table, show_edit_icon This will only enable you to see the cell's icon. nonetheless, You must create a new function and connect it to the cell on on_tap functionality.
Note:
Add property on_tap to the the cell
implement a new function
Update the page after change inside the new function
import flet as ft
def main(page: ft.Page):
# this is the function that controls the value of the cell
# returns value on tap
def updateOnTap(e):
e.control.content.value = "Hello John"
page.update()
page.add(
ft.DataTable(
columns=[
ft.DataColumn(ft.Text("First name")),
ft.DataColumn(ft.Text("Last name")),
],
rows=[
ft.DataRow(
cells=[
ft.DataCell(ft.Text("John"), show_edit_icon=True, on_tap=updateOnTap),
ft.DataCell(ft.Text("Smith")),
],
),
],
),
)
ft.app(target=main, view=ft.WEB_BROWSER)

switch plotly chart via button

I want to design the Dash app layout in such a way, that two trend/line charts are arranged in the same container/figure and I want to switch it with a button to display one chart at a time, the x-axis is the same for both charts.
I have tried with the below code but it doesn't update the label of the y-axis and hover text according to charts.
import pandas as pd
import plotly.express as px
dfx = pd.DataFrame({'months':['apr','may','jun','jul','aug','sep','oct','nov','dec','jan','feb','mar']
,'imported_qty':[25,35,45,30,35,45,50,25,30,35,45,40]
,'unit_price':[1.80,1.75,2.10,2.08,2.25,2.20,2.35,2.38,2.28,2.32,2.38,2.51]})
fig = px.line(dfx, x='months', y=dfx['imported_qty'])
fig.update_traces(mode="lines")
fig.update_layout(yaxis={'showgrid': False}
,xaxis={'showgrid': False}
,template='plotly_dark'
,hovermode="x"
,legend=dict(y=1, x=1, font=dict(size=8))
,height=350
,font=dict(size=10, color='gray')
,title={'text': "Import Qty. Trend"
,'y':0.95
,'x':0.5
,'xanchor': 'center'
,'yanchor': 'top'
,'font_size':15
,'font_color':'white'}
,updatemenus=[
dict(
type="buttons",
direction="right",
x=0.7,
y=1,
showactive=True,
buttons=list(
[
dict(
label="Qty",
method="update",
args=[{"y": [dfx['imported_qty']]}
,{'title':'Import Qty. Trend'}
,{'y':'Import qty.'}],
),
dict(
label="Price",
method="update",
args=[{"y": [dfx['unit_price']]}
,{'title':'Unit Price Trend'}
,{'y':'Unit Price'}],
),
]
),
)
]
)
Thank You.
Why not put you fig as dash Graph as a children of a html Div, create two buttons in the layout, and then create a callback that listens on these two buttons and that updates the children of the html Div depending on which button has been clicked ?

how to embed online plotly choropleth map link & script into existing Dash code

I have created an online Plotly choropleth map with US map with states getting data from an sqlite database...
I created an online html file at my plotly cloud account to be able to embed it in my custom Dash webpage that is currently at localhost. I could not find how to embed this online plotly graph into my existing Dash app.layout code so that I show everything in the same web page. Below is the overall code:
1) First i create an online Plotly choropleth map on my Plotly account. This works perfectly.
data = [ dict(
type='choropleth',
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
................................. Here I truncated the code for the sake of space................................
py.plot({"data":data, "layout":layout}, filename='US _Social_Sentiment_Map.html')
2) Then I retrieved the generated HTML link from my plotly account's embed HTML part for the above map. It looks something like this:
<div>
<img src="https://plot.ly/~myUser/2.png?share_key=qYb0mASJDFasdnfasdfASD" alt="US _Social_Sentiment_Map.html" style="max-width: 100%;width: 600px;" width="600" onerror="this.onerror=null;this.src='https://plot.ly/404.png';" />
<script data-plotly="sailor77:2" sharekey-plotly="qYb0mASJDFasdnfasdfASD"
src="https://plot.ly/embed.js" async></script>
</div>
3) Then I would like to embed the above Plotly choropleth map link into below python Dash code and publish the map at the resultant website at http://127.0.0.1:8050/. I could not figure out how to embed it despite different trials. My Dash code (without the above map link) looks like below (source: https://github.com/Sentdex/socialsentiment/blob/master/dash_mess.py )
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div(className='container-fluid', children=[html.H2('Live Twitter Sentiment', style={'color':"#CECECE"}),
html.H5('Search:', style={'color':app_colors['text']}),
dcc.Input(id='sentiment_term', value='twitter', type='text', style={'color':app_colors['someothercolor']}),
],
style={'width':'98%','margin-left':10,'margin-right':10,'max-width':50000}),
html.Div(className='row', children=[html.Div(id='related-sentiment', children=html.Button('Loading related terms...', id='related_term_button'), className='col s12 m6 l6', style={"word-wrap":"break-word"}),
html.Div(id='recent-trending', className='col s12 m6 l6', style={"word-wrap":"break-word"})]),
html.Div(className='row', children=[html.Div(dcc.Graph(id='live-graph', animate=False), className='col s12 m6 l6'),
html.Div(dcc.Graph(id='historical-graph', animate=False), className='col s12 m6 l6')]),
html.Div(className='row', children=[html.Div(id="recent-tweets-table", className='col s12 m6 l6'),
html.Div(dcc.Graph(id='sentiment-pie', animate=False), className='col s12 m6 l6'),]),
dcc.Interval(
id='graph-update',
interval=1*1000
),
dcc.Interval(
id='historical-update',
interval=60*1000
),
dcc.Interval(
id='related-update',
interval=30*1000
),
dcc.Interval(
id='recent-table-update',
interval=2*1000
),
dcc.Interval(
id='sentiment-pie-update',
interval=60*1000
),
], style={'backgroundColor': app_colors['background'], 'margin-top':'-30px', 'height':'2000px',},
)
Thanks for any suggestions or help.
Finally I solved how to add a plotly choropleth_map in my Dash code. Assuming you have installed the latest Dash releases, I had to make 3 changes to make it work.
First is to add the choropleth_map id under my 'app.layout = html.Div([ ' section as below.
html.Div(className='row', children= [html.Div(dcc.Graph(id='choropleth_map', style={"height": "100%", "width": "100%"}, config=dict(displayModeBar=True)), className='col s12 m6 l6'),
html.Div(dcc.Graph(id='sentiment-pie', animate=False), className='col s12 m6 l6')]),
Secondly, add the interval value so that the map is updated. This is under the 'app.layout' as well.
dcc.Interval(
id='choropleth_map-update',
interval=10*1000, n_intervals=0
),
Third, add below like section to call back the initial Dash declarations.
#app.callback(Output("choropleth_map", "figure"),
[Input('input-div', 'children'),
#Input(component_id='sentiment_term', component_property='value'),
Input('choropleth_map-update', 'n_intervals')])
def map_callback(sentiment_term, n_intervals):
#df = pd.read_csv(r'LOCAL PATH\mySourceFile.csv') #if you use a local CSV file
sql_term = "SELECT XXXX" # if you read from a database
df = pd.read_sql(sql_term, conn)
return choropleth_map(df, sentiment_term)
This worked for me well... Hope you can re-apply.

Categories