I have a dataframe tx_user_type_revenue:
I create a plot using plotly but for some reason it shows me an extra line. This code works fine for other data.
import plotly.plotly as py
import plotly.offline as pyoff
import plotly.graph_objs as go
#filtering the dates and plot the result
tx_user_type_revenue = tx_user_type_revenue.query("InvoiceYearMonth > 201601 and InvoiceYearMonth < 201901")
plot_data = [
go.Scatter(
x=tx_user_type_revenue.query("UserType == 'Existing'")['InvoiceYearMonth'],
y=tx_user_type_revenue.query("UserType == 'Existing'")['Revenue'],
name = 'Existing'
),
go.Scatter(
x=tx_user_type_revenue.query("UserType == 'New'")['InvoiceYearMonth'],
y=tx_user_type_revenue.query("UserType == 'New'")['Revenue'],
name = 'New'
)
]
plot_layout = go.Layout(
xaxis={"type": "category"},
title='New vs Existing Customers Revenue'
)
fig = go.Figure(data=plot_data, layout=plot_layout)
pyoff.iplot(fig)
Related
Hi I'm new to plotly dash. My objective is to draw a graph when excel sheet is updated.
The lines are updated when I add a new row to sheet but axises are not animated or updated. But when I refresh the browser it graph was updated and axis also updated. Here is my code. Any help would be highly appreciated
import dash
from datetime import datetime as dt
from dash.dependencies import Output, Input
from dash import dcc
from dash import html
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
def check_acc_data():
df = pd.read_excel("test.xlsx")
last_10_df = df.tail(10)
# print(last_10_df)
time_ = last_10_df['time'].values.tolist()
# time_2=["14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00","18:30"]
temp = last_10_df['temperature'].values.tolist()
humidity = last_10_df['Humidity'].values.tolist()
test_str = [date_obj.strftime('%H:%M') for date_obj in time_]
return test_str,temp,humidity
app = dash.Dash(__name__)
#fig = px.line(x=test_str, y=[temp, humidity])
app.layout = html.Div([
html.H4('Dashboard'),
dcc.Interval('graph-update', interval = 2000, n_intervals = 0),
html.Div(children='''
Temperature Humidity and Time variation.
'''),
dcc.Graph(
id='example-graph',
figure={},
animate=True
)
])
#app.callback(
dash.dependencies.Output('example-graph','figure'),
[dash.dependencies.Input('graph-update', 'n_intervals')])
def update_figure(n):
time1,temp1,humid1=check_acc_data()
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(x=time1, y=temp1, mode="lines+markers", name='Temperature'),
secondary_y=False
)
fig.add_trace(
go.Scatter(x=time1, y=humid1, mode="lines+markers", name='Humidity'),
secondary_y=True,
)
fig.update_layout(yaxis=dict(range=[-2.5,50]),
yaxis1=dict(range=[-2.5,100]),
)
return fig
if __name__ == '__main__':
app.run_server(debug=True, port=10451)
import dash
from dash import Dash, html, dcc, Output, Input, callback
import plotly.graph_objects as go
import plotly.express as px
df1 = pd.read_csv(filepath+filename, index_col="Date")
df1.index = pd.to_datetime(df1.index)
df1["Measure1_SMA"] = df1["Measure1"].rolling(20).mean()
df1["Measure2_SMA"] = df1["Measure2"].rolling(20).mean()
app = Dash(__name__)
my_dropdown = dcc.Dropdown(options = ['Measure1', 'Measure2'],
value = df1.columns[:2],
multi = False,
style = {'width':'50%'})
my_graph = dcc.Graph(figure={})
app.layout = html.Div([
html.H1('Metrics (Values)', style = {'textAlign':'center'}),
html.Label("Metrics: "),
my_dropdown,
my_graph
])
#callback(
Output(component_id=my_graph, component_property='figure'),
Input(component_id=my_dropdown, component_property='value')
)
def update_graph(dropdown_value):
plot_figure = px.bar(data_frame=df1, y=dropdown_value, x=df1.index)
#plot_figure.add_line()
print(dropdown_value)
return plot_figure
if __name__ == "__main__":
app.run_server(debug=True)
I want to create a single plot on the plotly dashboard with an option to toggle between Measure1 and Measure2. Selecting the dropdown_value will create a bar graph of Measure1 on y-axis and Date on x-axis. I also want to plot a line graph on the same plot which will be the rolling average of previous 20 days for the value selected from the dropdown.
I tried adding a add_line() method but not sure how to use it.
Creates a data frame from which the value columns and SMA columns are extracted, using the values obtained from the drop-down selections. Draw a bar graph in the created data frame and add the SMA in scatter plot line mode. drawing two graphs, I think I need to make a graph with two axes. since I could not add graphs to px.line, I reused the data in px.line to create the first I have used the data from px.line as the first graph. The sample data is stock price data.
import dash
from dash import Dash, html, dcc, Output, Input, callback
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import yfinance as yf
df1 = yf.download("AAPL", start="2021-01-01", end="2021-03-01")
df1["Close_SMA"] = df1["Close"].rolling(20).mean()
df1["High_SMA"] = df1["High"].rolling(20).mean()
df1 = df1[['High','Close','Close_SMA','High_SMA']]
app = Dash(__name__)
my_dropdown = dcc.Dropdown(options = ['Close', 'High'],
value = 'Close',
multi = False,
style = {'width':'50%'})
my_graph = dcc.Graph(figure={})
app.layout = html.Div([
html.H1('Metrics (Values)', style = {'textAlign':'center'}),
html.Label("Metrics: "),
my_dropdown,
my_graph
])
#callback(
Output(component_id=my_graph, component_property='figure'),
Input(component_id=my_dropdown, component_property='value')
)
def update_graph(dropdown_value):
sma = '{}_SMA'.format(dropdown_value)
dff = df1[[dropdown_value,sma]]
dff = dff.dropna()
plot_figure = make_subplots(specs=[[{"secondary_y": True}]])
fig = px.bar(data_frame=dff, y=dropdown_value, x=dff.index)
plot_figure.add_trace(fig.data[0], secondary_y=False)
plot_figure.add_trace(go.Scatter(x=dff.index, y=dff[sma], name=sma, mode='lines'), secondary_y=True)
plot_figure.update_layout(yaxis_title='Close')
return plot_figure
if __name__ == "__main__":
app.run_server(debug=True)
I'm not clear how I could dynamically create multiple charts at once - or if that is not possible then how I could loop through a list of values using a single callback.
For example in the code below list of continents is a a list of filter options. Is it possible to basically make it so when this page loads, I see 5 charts automatically?
Currently, what I'm doing is I have to type 5 #app.callback...make_scatter_plot(option=_dropdown_value) which ends up with a million lines of code in my file and makes it hard to read even though everything is doing the same thing.
What am I missing? Thanks
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
import numpy as np
app = Dash(__name__)
df = px.data.gapminder()
list_of_continents = ["Asia", "Africa", "Europe", 'Oceania', 'Americas']
app.layout = html.Div([
html.H4('Restaurant tips by day of week'),
dcc.Dropdown(
id="dropdown",
options=list_of_continents,
multi=False
),
dcc.Graph(id="graph"),
#dcc.Graph(id ='graph2') ##????
])
#app.callback(
Output("graph", "figure"),
Input("dropdown", "value")
)
def make_scatter_plot( value =[i for i in list_of_continents], df = df):
"""
"""
data = df[df['continent'].isin([value])]
fig = px.scatter(data, x="lifeExp", y="gdpPercap",
size="pop")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
although plotly express can help you set up a graph with just one line of code it’s not very handy when it comes to customizing each trace. So, for that, you’ve to switch to graphs_objects.
In the following lines of code, the callback generates a Graph component for each trace and appends each graph component to a Div component. Hence you get multiple graphs using a single callback.
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
app = Dash(__name__)
df = px.data.gapminder()
app.layout = html.Div([
html.H4('Restaurant tips by day of week'),
html.Div(id='graphs',children=[])
])
#app.callback(
Output("graphs", "children"),
Input("graphs", "children")
)
def make_scatter_plot(child):
"""
"""
for continent in df['continent'].unique():
df_filtered = df[df['continent'] == continent]
fig = go.Figure()
fig.add_trace(
go.Scatter(x = df_filtered['lifeExp'],
y = df_filtered['gdpPercap'],
mode = 'markers',
marker = dict(size = 10 + (df_filtered['pop'] - df_filtered['pop'].min()) * 20
/ (df_filtered['pop'].max() - df_filtered['pop'].min())) # This is just to scale the marker size value between 10 and 20.
)
)
fig.update_layout(
title_text = continent
)
child.append(dcc.Graph(figure=fig))
return child
if __name__ == '__main__':
app.run_server(debug=True)
The output of the Code:
Click here
I want to use bar and line chart in same axis with bar having a color code based on a different variable and pass that as a return in Dash.In plotly express a color argument is passed into trace but in dash its not retruning fig to dcc.graph.Can someone advice me where I am going wrong ?
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
import time
import plotly.express as px
import numpy as np
pd.set_option(‘display.width’, 400)
pd.set_option(‘display.max_columns’, 50)
df1 = pd.read_csv(r"E:\OI\test_mar_2020.csv")
df1[‘Date’] = pd.to_datetime(df1[‘Date’])
df1[‘Monthly_Exp_End’] = pd.to_datetime(df1[‘Monthly_Exp_End’])
df1[‘Monthly_Exp_Start’] = pd.to_datetime(df1[‘Monthly_Exp_Start’])
df1[‘Monthly_exp_end_ind’] = np.where(df1[‘Monthly_Exp_End’]==df1[‘Date’] , True, False)
df = df1[df1[‘Year’].isin([2020])]
external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]
app = dash.Dash(name, external_stylesheets=external_stylesheets)
party_data =
for client in df[‘Client_Type’].unique():
party_data.append({‘label’: client, ‘value’: client})
app.layout = html.Div([
html.Div([
dcc.Dropdown(id=‘client-picker’,options=party_data,value= ‘Test1’ )]),
dcc.Graph(id=‘graph’)
])
#app.callback(Output(‘graph’, ‘figure’), [Input(‘client-picker’, ‘value’)])
def update_figure(client_picker_name):
df_new = df[df.Client_Type == client_picker_name]
I want to add a color argument lile plotly.express— fig = px.scatter(df, x=“sepal_width”, #y=“sepal_length”, color=“species”) into below trace1
trace1 = go.Bar(x=df_new.Date, y=df_new.colA)
trace2 = go.Bar(x=df_new.Date, y=df_new.colB)
trace3 = go.Scatter(x=df_new.Date, y=df_new.colC, mode=‘lines+markers’, yaxis=‘y2’)
return {
‘data’ : [trace1,trace2,trace3]
}
if name == ‘main’:
app.run_server(debug=True,port = 8080)
You need to pass color parameter inside marker.
trace1 = go.Bar(x=df_new.Date, y=df_new.colA, marker=dict(color='green'))
I am working on choropleth using plotly in Jupyter Notebook.I want to plot choropleth but its showing me empty output.I am working with offline plotly.In html its genrated chart successfuly but when i tried offline it shows me empty output.please tell me how i solve this error.
here is my code
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.offline.offline import _plot_html
init_notebook_mode(connected=True)
for col in state_df.columns:
state_df[col] = state_df[col].astype(str)
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
state_df['text'] = state_df['StateCode'] + '<br>' +'TotalPlans '+state_df['TotalPlans']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = state_df['StateCode'],
z = state_df['TotalPlans'].astype(float),
locationmode = 'USA-states',
text = state_df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = 'Plan by States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
plotly.offline.iplot(fig)
You are passing a dictionary to iplot which in contradiction to the documentation can handle only Figure objects and not dictionaries.
Try
fig = Figure(data=[data], layout=layout)
and it should work.