I am using the RangeSlider in Python Dash. This slider is supposed to allow users to select a range of dates to display, somewhere between the minimum and maximum years in the dataset. The issue that I am having is that each mark shows as 2k due to it being automatically rounded. The years range between 1784 and 2020, with a step of 10 each time. How do I get the marks to show as the actual dates and not just 2k? This is what I have below.
dcc.RangeSlider(sun['Year'].min(), sun['Year'].max(), 10,
value=[sun['Year'].min(), sun['Year'].max()], id='years')
You can use attribute marks to style the ticks of the sliders as follows:
marks={i: '{}'.format(i) for i in range(1784,2021,10)}
The full code:
from dash import Dash, dcc, html
app = Dash(__name__)
app.layout = html.Div([
dcc.RangeSlider(1784, 2020,
id='non-linear-range-slider',
marks={i: '{}'.format(i) for i in range(1784,2021,10)},
value=list(range(1784,2021,10)),
dots=False,
step=10,
updatemode='drag'
),
html.Div(id='output-container-range-slider-non-linear', style={'margin-top': 20})
])
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Output
Related
In the dash application, I have a map displayed with the center in my position and on it I have a point (mark) in the center again as my position. However, I need to dynamically change my position on the map.
The map itself changes its center without problems, but the point (marker) does not, as if it is anchored in its original position and does not move to a new position (the new center of the map).
Here is a simple code that shows it nicely. After running it, the map is redrawn every 2 seconds as I want. But the point remains in the last-origial position..... Does anyone know what I'm doing wrong?
import random
import dash
from dash import dcc,html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
def get_fig():
# random position as center
lat = 48.8 + 1/random.randrange(300, 800)
lon = 20.1+ 1/random.randrange(300, 800)
fig = go.Figure()
# blue point - should be in center of map , vhy is not ?
fig.add_trace(
go.Scattermapbox(
lat=[lat],
lon=[lon],
mode="markers",
marker=go.scattermapbox.Marker(size=20),
)
)
# open street map with center at lat:lon
fig.update_layout(
height=552,
width=640,
margin={"r": 2, "t": 2, "b": 2, "l": 2},
autosize=True,
mapbox=dict(style="open-street-map", center=dict(lat=lat, lon=lon), zoom=16),
)
return fig
app = dash.Dash()
#app.callback(
Output("graph", "figure"),
Input("my_interval", "n_intervals"))
def update_bar_chart(dummy):
return get_fig()
app.layout = html.Div([
dcc.Graph(id = "graph"),
dcc.Interval(id="my_interval", interval=2000, n_intervals=0, disabled=False),
])
app.run_server(debug=True, use_reloader=False)
I use python 3.9 , plotly version is 5.11.0 and dash version is 2.7.0
I've tried several different ways, but they all fail in the same way.
I'm going through the Dash Tables design to create a webpage with data preview, But the problem I'm facing is it's not responsive to browser, Though Column wise it's responsive enough but the height it's not helping at all. I'm using the bellow python code for the same.
from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict
app = Dash(__name__)
df = pd.DataFrame(OrderedDict(
[
[
'Column {}'.format(i + 1), list(range(30))
] for i in range(15)
]
))
app.layout = dash_table.DataTable(
data=df.to_dict('records'),
columns=[{'id': c, 'name': c} for c in df.columns],
virtualization=True,
fixed_rows={'headers': True},
style_cell={'minWidth': 95, 'width': 95, 'maxWidth': 95},
style_table={"overflowY":"auto",'maxHeight':'75vh'} # default is 500
)
if __name__ == '__main__':
app.run_server(debug=True)
I'm not getting any proper config to make it responsive height wise. Few ref. doc's I've came across are as follows:
https://dash.plotly.com/datatable/height
https://dash.plotly.com/datatable/style
https://community.plotly.com/t/dash-data-table-not-displayed-on-full-page/68332/14
Adjusting the MaxHeight of a Table in Dash Tables Python
Can someone help here? How can I make this table fully responsive for any screen size ?
I have restaurant name, cusines, lat , long as columns. The map I am trying to show on the html page is not updating as per the filter , It shows all the restaurnats.
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
app = dash.Dash('app')
df = pd.read_excel('Resturants.XLSX')
app.layout = html.Div([
html.H1('Resturant map by cusine', style={'text-align': 'center'} ),
dcc.Dropdown(id='cusine_dd',
options=[{'label': i, 'value': i} for i in df.cusines.unique()],
value = 'Chinese',
style={'width':'40%'}),
html.Div(id= 'output', children =[] ),
dcc.Graph(id='mapbycusine', figure={})
])
#app.callback(
[Output(component_id='output', component_property='children'),
Output(component_id='mapbycusine', component_property='figure')],
[Input(component_id='cusine_dd', component_property='value')]
)
def update_figure(input_cusine):
#cusine_filter = 'All'
container = f"Currently showing {input_cusine}"
df_copy = df.copy(deep=True)
if input_cusine:
df_copy = df_copy[df_copy['cusines'] == input_cusine]
print(df_copy.head())
fig = px.scatter_mapbox(data_frame=df_copy, lat='Latitude', lon='Longitude', zoom=3, height=300, hover_data= ['cusines'])
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(height=1000, margin={"r":100,"t":100,"l":100,"b":300})
return container, fig
if __name__ == '__main__':
app.run_server(debug=True)
I am checking every step just to make sure if input and output is working I have used countainers updates on the html page and print the df_copy after filtering data as per the input cusine. The containers give the correct output and the df.copy.head() shows only filltered columns in the console but the map on html dash app is not updating.
I want the map to show the restaurants for just the selected cusine
I cannot reproduce your error, but perhaps some of the steps I took in debugging might prove helpful:
First, I took the first 100 rows of a restaurant dataset from kaggle, and then randomly assigned three different cuisine types to each unique restaurant name. Then when creating the fig object with px.scatter_mapbox, I passed the cuisine column to the color argument and a mapping between cuisine and color to the color_discrete_map argument so that the marker colors will be different when you select different cuisine types from the dropdown.
This is the result, with visible changes between the marker locations as well as the marker colors (depending on the dropdown selection). Also, as you mentioned, the print outs of df_copy from inside your update_figure function match the dropdown selections as expected.
As far as I can tell, the only thing fundamentally different between your dashboard and mine would be the data that was used. Maybe it is possible that you have a bunch of duplicate rows that span multiple cuisines (i.e. imagine I took a data set of only Mexican restaurants, then duplicated all of the rows but switched the cuisine to Italian – then if you select Mexican or Italian from the dropdown, the result would be the same because you're plotting all of the same latitudes and longitudes in each case so the figure wouldn't appear to change, and you might not catch this from examining the df_copy print outs).
Can you verify that your data set doesn't contain duplicate latitude and longitude points with different cuisines assigned to the same point?
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import plotly.express as px
app = dash.Dash('app')
# df = pd.read_excel('Resturants.XLSX')
## create a small restaurant dataset similar to yours
## downloaded from: https://www.kaggle.com/datasets/khushishahh/fast-food-restaurants-across-us?resource=download
df = pd.read_csv('Fast_Food_Restaurants_US.csv', nrows=100, usecols=['latitude','longitude','name'])
df.rename(columns={'latitude':'Latitude', 'longitude':'Longitude'}, inplace=True)
## randomly assign some cuisine types to unique restaurant names
unique_names = df['name'].unique()
np.random.seed(42)
name_cuisine_map = {
name:cuisine for name,cuisine in
zip(unique_names, np.random.choice(['American','Mexican','Chinese'], size=len(unique_names)))
}
cuisine_color_map = {
'American':'blue',
'Mexican':'green',
'Chinese':'red'
}
df['cusines'] = df['name'].map(name_cuisine_map)
df['color'] = df['cusines'].map(cuisine_color_map)
app.layout = html.Div([
html.H1('Resturant map by cusine', style={'text-align': 'center'} ),
dcc.Dropdown(id='cusine_dd',
options=[{'label': i, 'value': i} for i in df.cusines.unique()],
value = 'Chinese',
style={'width':'40%'}),
html.Div(id= 'output', children =[] ),
dcc.Graph(id='mapbycusine', figure={})
])
#app.callback(
[Output(component_id='output', component_property='children'),
Output(component_id='mapbycusine', component_property='figure')],
[Input(component_id='cusine_dd', component_property='value')]
)
def update_figure(input_cusine):
#cusine_filter = 'All'
container = f"Currently showing {input_cusine}"
df_copy = df.copy(deep=True)
if input_cusine:
df_copy = df_copy[df_copy['cusines'] == input_cusine]
print("\n")
print(df_copy.head())
fig = px.scatter_mapbox(data_frame=df_copy, lat='Latitude', lon='Longitude', zoom=3, height=300, hover_data= ['cusines'], color='cusines', color_discrete_map=cuisine_color_map)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(height=1000, margin={"r":100,"t":100,"l":100,"b":300})
return container, fig
if __name__ == '__main__':
app.run_server(debug=True)
I'm trying to build a dashboard with Dash from Plotly composed of a series of tiles (Text) like in the picture below.
I'm trying to build a component to reuse it an build the layout below. Each box will contain a Title, a value and a description as shown below.
Is there a component available? Can someone help me with any basic idea/code ?
Thanks in advance!
I would recommend checking out Dash Bootstrap Components (dbc).
You can use dbc.Col (columns) components nested into dbc.Row (rows) components to produce your layout. You can check them out here.
Then for the actual 'cards' as I'll call them, you can use the dbc.Card component. Here's the link.
Here's some example code replicating your layout:
import dash_bootstrap_components as dbc
import dash_html_components as html
card = dbc.Card(
dbc.CardBody(
[
html.H4("Title", id="card-title"),
html.H2("100", id="card-value"),
html.P("Description", id="card-description")
]
)
)
layout = html.Div([
dbc.Row([
dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
]),
dbc.Row([
dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
]),
dbc.Row([
dbc.Col([card]), dbc.Col([card])
])
])
Best thing would probably be to have a function which creates those cards with parameters for ids, titles and descriptions to save the hassle of creating different cards:
def create_card(card_id, title, description):
return dbc.Card(
dbc.CardBody(
[
html.H4(title, id=f"{card_id}-title"),
html.H2("100", id=f"{card_id}-value"),
html.P(description, id=f"{card_id}-description")
]
)
)
You can then just replace each card with create_card('id', 'Title', 'Description') as you please.
Another quick tip is that the col component has a parameter, width. You can give each column in a row a different value to adjust the relative widths. You can read more about that in the docs I linked above.
Hope this helps,
Ollie
I have a dataset and I want to plot some graphs. I created a plotly graph that loads correctly with a callback function where I can select the year I want the data. The dataset loads correctly and there are no missings or errors. But Whenever I try to change the data nothing happens.
my dataset has columns like this
codass Q NF CURS
240011 1 7 2010
240011 2 5 2010
240012 1 2 2011
I tried starting with a blank graph, and nothing happens. The data is fine cause the initial graph loads correctly it's on the updating procedure.
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_html_components as html
import plotly.graph_objs as go
FaseIni = pd.read_csv('/Users/Jordi/Documents/Universitat/TFG/tfg/Spyder path/qfaseini18.csv',sep=';',encoding='utf-8')
Q=[1,2]
anys=FaseIni['CURS'].unique()
pv = FaseIni.pivot_table( index=['CODASS'], columns=['Q'], values=['NF'], fill_value=0)
trace1=go.Bar(x=pv.index, y =pv[('NF',1)],name='q1')
trace2=go.Bar(x=pv.index, y =pv[('NF',2)],name='q2')
app = dash.Dash()
app.layout = html.Div([
html.Div([
dcc.Dropdown(
id='Anys',
options= [{'label':'2010' , 'value':2010 },{'label':'2011' , 'value':2011 }],
value =2010,
)
]),
html.Div([
dcc.Graph(
id='notes',
figure={
'data':[trace1,trace2]
}
)
])
])
#app.callback(
Output('notes','figure'),
[Input('Anys','value')])
def update_graph(Anys):
pv2 = FaseIni.loc[FaseIni['CURS'] == Anys]
pv2 = pv2.pivot_table( index=['CODASS'], columns=['Q'], values=['NF'],
fill_value=0)
trace3=go.Bar(x=pv2.index, y =pv2[('Anys',1)],name='q1')
trace4=go.Bar(x=pv2.index, y =pv2[('Anys',2)],name='q2')
return {'data':[trace3,trace4]}
The initial graph loads correctly, it just doesn't update
I had this problem the other day. I'm not sure if this will troubleshoot it because I don't have the csv file to test it but try changing to this:
trace3=go.Bar(x=pv2.index, y =pv2[(value,1)],name='q1')
trace4=go.Bar(x=pv2.index, y =pv2[(value,2)],name='q2')