Make button coloured in plotly express - python

I have the following button in plotly express:
fig.update_layout(
shapes=[vertical_line],
updatemenus=[
dict(
type="buttons",
buttons=[
dict(label="Toggle Shapes",
method="relayout",
args=[{
"shapes": [vertical_line],
"annotations": vline_annotation}],
args2=[{
"shapes": rectangle_shape + [vertical_line],
"annotations": rectangle_annotation+ vline_annotation}],
),
],
)
]
)
This button is too bright for the plotly_dark theme, and is thus unreadable. I would like to change the color, however it seems this button doesn't have a parameter to set color in plotly express (to the best of my knowledge). How would I make this button green?

I think you can use the bgcolor at the updatemenus level (not the button level) (docs):
updatemenus=[
dict([
type="buttons",
buttons=[
#...
],
bgcolor = "#222",
bordercolor = "#FFF",
borderwidth = 0.5
])
]

Related

Button option in plotly python to switch graph display between two different data sets

I'm trying to introduce buttons in plotyly express to switch between datasets and display the same in as stacked graph with color options.
fig.update_layout(
autosize=True,
title=title,
title_x=0.5,
title_xref='paper',
title_yref='paper',
xaxis_domain = [0, 0.98],
xaxis_title=None,
yaxis_title=yaxis_title,
font_color='#505050',
font_family='helvetica',
paper_bgcolor='#ffffff ',
plot_bgcolor='#ffffff ',
margin=dict(pad=20),
showlegend=True,
updatemenus=[
dict(
type="buttons",
direction="right",
x=0.55,
y=1.03,
showactive=True,
buttons=list(
[
dict(
label="A1",
method="update",
args=[
{"visible": [True, False]},
{"y":[df_old['X']]},
],
),
dict(
label="B1",
method="update",
args=[
{"visible": [False, True]},
{"y":[df_new[X']]},
],
),
]
In the above code and in the updatemenus how do i use different datasets df_old and df_new?

Plotly Dash Boostrap drop down menu is rendered behind the the plotly graph objects. Is there a way to stop this?

I'm making a plotly - dash app that has a navigation side bar to browse through the different app pages (see code below). One of the navigation items contains a dbc.DropDownMenu that hangs over the edge of the navigation side bar into the main content area.
Most of the the time this isn't an issue, except when there are plotly graphs in the main content area. When there are graphs, the drop down menu is rendered below the graphs (see pictures). Is it possible to change the render order always have the drop down shown on top?
# styling the sidebar
SideBar_Style = {
"position": "fixed",
"top": 0,
"left": 0,
"bottom": 0,
"width": "18rem",
"padding": "2rem 1rem",
"background-color": "#f8f9fa",
}
# padding for the page content
Content_Style = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
}
sidebar = html.Div(
[
html.H2("Navigation", className="display-4"),
html.Hr(),
html.P(
"Select a page", className="lead"
),
dbc.Nav(
[dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Timeseries", href="/pages/timeseries",
active="exact"),
dbc.NavItem(
dbc.Row([
dbc.Col(dbc.NavLink("Wind Roses",
href="/pages/windrose", active="exact"), width=10),
dbc.Col(dbc.DropdownMenu([dbc.DropdownMenuItem("Comparison", href="/pages/windrosecomparison", active="exact"),
dbc.DropdownMenuItem("Item 2")], nav=True), width=2)], className="g-0")
),
dbc.NavLink("Monthly Wind Speeds",
href="/pages/monthwindspeeds", active="exact"),
dbc.NavLink("Recovery", href="/pages/recovery",
active="exact"),
dbc.NavLink("Wind Shear", href="/pages/windshear",
active="exact"),
dbc.NavLink("Diurnal", href="/pages/diurnal", active="exact"),
dbc.NavLink("Campaign Map",
href="/pages/campaignmap", active="exact"),
dbc.NavLink("TestPage", href="/pages/testpage",
active="exact"),
],
vertical=True,
pills=True,
),
],
style=SideBar_Style,
)
content = html.Div(id="page-content", children=[], style=Content_Style)
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
sidebar,
content
])
As suggested by Daniel Al Mouiee, changing the Z-Index of the graphs parent container fixed the issue

Plotly Update Button to Filter Dataset

I am brand new to the world of Python and Plotly and have been working on a Capstone project with the following objective:
Create an interactive chart that allows the user to view US Vehicle Sales between 2019-2021
that allows the user to view the data by Body Type, Segment, Year, Make/Brand, and Individual Models.
I have learned how to add buttons using Plotly Express, though I have been having issues with making them toggle the way I want them to. Here is a snippet of my code:
segbar = px.bar(segments, x=segments.Month, y=segments.NumSold, color=segments.NumSold,
color_continuous_scale='inferno', custom_data=[segments.Segment, segments.PrimaryBodyType, segments.Month, segments.Year], barmode='group')
segbar.update_traces(hovertemplate='<b>Segment:</b> %{customdata[0]} %{customdata[1]}<br><b>Units Sold:</b> %{y:,.0f}<br>Date: %{customdata[2]} %{customdata[3]}')
segbar.update_layout(
updatemenus=[
dict(
type="dropdown",
direction="down",
bgcolor='Dark Blue',
buttons=list(
[
dict(
label="(All)",
method="update",
args=[{"y": segments.NumSold},
{"x": segments.Month}],
),
dict(
label="2021",
method="update",
args=[{"y": segments.loc[segments['Year'] == "2021", "NumSold]},
{"x": segments.loc[segments['Year] == "2021", "Month"]}]
)
]),
), dict(
type="dropdown",
direction="down"
)
], template='plotly_dark')
segbar.show()
The default view (first button) seems to be working fine, though when I select the other button to filter by rows with a "Year" value of 2021, this is the output:
You are pretty close – you just need to add another set of square brackets around the pd.Series you are passing to "y" and "x" in the args key of the dictionaries. To get the example to work, I had to modify your DataFrame slightly, but this should work with your DataFrame.
from io import StringIO
import pandas as pd
import plotly.express as px
segment_data = StringIO("""Segment|PrimaryBodyType|Month|Year|NumSold|MonthNum(Index)|Compact|
A|SUV|January|2021|254391|0|Compact|
B|SUV|January|2019|249913|0|Midsize|
C|SUV|January|2021|248762|0|Midsize|
D|SUV|January|2020|239102|0|Compact|
E|SUV|January|2020|233614|0|Compact|
""")
segments = pd.read_csv(segment_data, sep="|")
segments["Year"] = segments["Year"].astype(str)
segbar = px.bar(segments, x=segments.Month, y=segments.NumSold, color=segments.NumSold,
color_continuous_scale='inferno', custom_data=[segments.Segment, segments.PrimaryBodyType, segments.Month, segments.Year], barmode='group')
segbar.update_traces(hovertemplate='<b>Segment:</b> %{customdata[0]} %{customdata[1]}<br><b>Units Sold:</b> %{y:,.0f}<br>Date: %{customdata[2]} %{customdata[3]}')
segbar.update_layout(
updatemenus=[
dict(
type="dropdown",
direction="down",
bgcolor='Dark Blue',
buttons=list(
[
dict(
label="(All)",
method="update",
args=[{"y": [segments.NumSold]},
{"x": [segments.Month]}],
),
dict(
label="2021",
method="update",
args=[{"y": [segments.loc[segments['Year'] == "2021", "NumSold"]]},
{"x": [segments.loc[segments['Year'] == "2021", "Month"]]}]
)
]),
), dict(
type="dropdown",
direction="down"
)
], template='plotly_dark')
segbar.show()

plotly-dash: embed indicator graph inside of a dbc card

I have been banging my head off the wall all day and cannot find a way to fit a dash indicator inside of a dash_bootstrap_components card.
It seems that the body of the card and the graph do not live inside of the card. I am not very familiar with dash so it is difficult to find a way to solve the issue.
here is what I have been able to do so far in terms of plotting the indicator:
fig3 = go.Figure()
fig3.add_trace(go.Indicator(
mode = "number+delta",
number = {"font":{"size":40},'prefix': "$"},
value = 2045672,
delta = {'reference': 30000},
gauge = {'shape': "bullet"},
title = {"text": "On Hand<br><span style='font-size:0.9em;color:gray'></span>"},
#title='Stock On Hand',
domain = {'x': [0, 1], 'y': [0, 1]},
))
fig3.update_layout(paper_bgcolor = "rgba(0,0,0,0)",
plot_bgcolor = "rgba(0,0,0,0)",
autosize=False,
width = 200,
height=200,
)
fig3.update_traces(align="center", selector=dict(type='indicator'))
I am forced to specify width and height for the indicator otherwise it is way too big, however this cause issues because its size does not adjust in regards to the card.
here is the html dash code for the box and the plot:
html.Div(children=[
html.Div(children=[
html.Div(children=[
html.Div(children=[
dbc.Card(
[dbc.CardBody(
[dcc.Graph(figure=fig3)
]
)],className="card", style={"width": "15rem", "height":"8rem"}
),
], className='jumbotron', style={'background-color': '#fffffff'}),
])
],className="col-3 mx-auto"),
],className="row p-0 h-100", style={'background-color': '#f7f7f7', 'height':110}),
], className="full-width p-0 h-100", style={'background-color': '#fffffff'}),
and here is what the final output looks like:
I am not sure what else I can try to bring the graph inside of the box, any help would be appreciated
Remove the instances where you set the height in the style of dash components and the indicator doesn't get cut off.
So you can do something like this:
app.layout = html.Div(
children=[
html.Div(
children=[
html.Div(
children=[
html.Div(
children=[
dbc.Card(
[
dbc.CardBody(
[dcc.Graph(figure=fig3)],
style={"width": "15rem"},
)
]
)
],
className="jumbotron",
style={"backgroundColor": "#fffffff"},
)
],
className="col-3 mx-auto",
)
],
className="row p-0 h-100",
style={"backgroundColor": "#f7f7f7"},
)
],
className="full-width p-0 h-100",
style={"backgroundColor": "#fffffff"},
)
I've also changed the casing of the style properties to camelCase as this is what React (which dash uses) likes.

How to update choropleth map in Dash

I'm making a webapp using Python and Dash, this webapp includes a choropleth map of the world with data based on the selected year. I want to be able to change the year and with that also update the map to match that year. I prefer to do this with the Dash slider, although any other way I would appreciate as well.
I've tried updating other graphs such as line charts with the text input, and that worked, but when i changed it to a choropleth map it stopped updating. It now only creates the map but updates on it don't show up. I've put some print text in the update function and it confirmed that it is actually called when I change the input, but the graph just doesn't update.
The layout:with the dcc.input i want to update the html.Div 'my-div'
app.layout = html.Div( children=[
html.H1(
children='UN Sustainable Development goal: Poverty',
style={
'textAlign': 'center',
'color': colors
}
),
dcc.Input(id='my-id',value='30', type='text'),
html.Div(id='my-div')
,
daq.Slider(
id='my-daq-slider',
min=1,
max=sliderlength,
step=1,
),
html.Div(id='slider-output')
], style={
'textAlign': 'center'
})
The update part
#app.callback(
Output('my-div', 'children'),
[Input('my-id', 'value')])
def update_output_div(input_value):
return dcc.Graph(
id='my-div',
figure={'data': [go.Choropleth(
locations = df_pov['Country Code'],
z = df_pov.iloc[:,int(input_value)],
text = df_pov['Country Name'],
autocolorscale = True,
reversescale = False,
marker = go.choropleth.Marker(
line = go.choropleth.marker.Line(
color = 'rgb(180,180,180)',
width = 0.5
)),
colorbar = go.choropleth.ColorBar(
tickprefix = '%',
title = '% below 1.90$ '),
)],
'layout': go.Layout(
title = go.layout.Title(
text = list(df_pov)[int(input_value)]
),
geo = go.layout.Geo(
showframe = False,
showcoastlines = False,
projection = go.layout.geo.Projection(
type = 'equirectangular'
)
),
annotations = [go.layout.Annotation(
x = 0.55,
y = 0.1,
xref = 'paper',
yref = 'paper',
text = 'Source: Kaggle',
showarrow = False
)]
)
}
)
What i expected: for the choropleth to update when changing the text input, or slider input.
Actual: the map gets created once ( with the same function that should update it), but doesn't update.
Dash doesn't like new components being loaded in like this. Try initializing your graph by adding an empty graph to the layout like this:
html.Div(id='my-div', children=[
dcc.Graph(
id='my-graph-id',
figure=dict(
data=[],
layout={},
),
)
])
With the graph already on the page, you would have to change the callback so that it updates the figure prop of the Graph instead of the children of the div.
Also, you have multiple IDs that are the same. Dash doesn't like that. Make sure every ID is unique. If all of this still does not work, I may need to ask you to post some more details so I can help further. Good luck!

Categories

Resources