How to create a vertical scroll bar with Plotly? - python

I would like to create a vertical scroll for a line chart in Plotly. For visualisation, the vertical scroll is something depicted in the figure below.
Assume, we have 6 line chart as below, then how can we create a vertical scroll bar on the canvas
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import pandas as pd
# data
pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df = df.set_index('Date')
df.tail()
cols = df.columns[:-4]
ncols = len(cols)
# subplot setup
fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)
for i, col in enumerate(cols, start=1):
fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1)
fig.show()
Thanks for any tips or good reading material.

I made a single page web app using plotly-dash. In this dashboard I wanted to create a vertical bar chart that also had a sroller on the side.
I imported the following dependencies:
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash
import dash_table
import plotly.graph_objs as go
import pandas as pd
In the app.layout I gave the css style parameters in the html.Div that contained my dcc.graph component:-
dcc.Graph(
id='doctors',
figure={}
),style={"maxHeight": "400px", "overflow": "scroll"})
], width={'size': 6})
Later in the #app callback I gave height to my vertical bar graph:-
fig.update_layout(height = (30*len(all_by_doctor)), title_text='Total bookings
by {} doctors'.format(len(all_by_doctor)),plot_bgcolor='#ffffff')

Related

Plotly combined barplot and table controled by range slider

I'm currently trying to create a graph with plotly,
My goal would be to create a combined Barplot / Data table both controled with a range slider in order to controle the values with the date. I've succeded to create the barplot controled with the range slider.
I can't manage to control the table :/
Here is a combined plot but where the range slider is attached to the table, as you can see it does not control the date but the table view
https://plotly.com/~tristan1551/31/
Here is an exemple of a barplot i've done with a range slider https://plotly.com/~tristan1551/23/
Another idea would be to only to control the table with the ranger slider, i can't manager to do that too.
Is there a way to achive what i want to do ?
Thank you for your herlp :)
to synchronise a table with a range slider on a figure you can use a dash callback
below code creates a bar chart with a rangeslider
attaches a callback to changes in figure to get position of rangeslider
constructs table based on these inputs
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv")
df["AAPL_x"] = pd.to_datetime(df["AAPL_x"])
fig = px.bar(df, x="AAPL_x", y="AAPL_y").update_layout(
xaxis={
"range": [df["AAPL_x"].quantile(0.9), df["AAPL_x"].max()],
"rangeslider": {"visible": True},
}
)
# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
[dcc.Graph(id="bargraph", figure=fig), html.Div(id="bartable", children=[])],
)
#app.callback(
Output("bartable", "children"),
Input("bargraph", "relayoutData"),
)
def updateTable(graphData):
global df
if graphData and "xaxis.range" in graphData.keys():
d1 = pd.to_datetime(graphData["xaxis.range"][0])
d2 = pd.to_datetime(graphData["xaxis.range"][1])
else:
d1 = df["AAPL_x"].quantile(0.9)
d2 = df["AAPL_x"].max()
dft = df.loc[df["AAPL_x"].between(d1, d2)]
return dash_table.DataTable(
columns=[{"name": c, "id": c} for c in dft.columns],
data=dft.to_dict("records"),
)
# Run app and display result inline in the notebook
app.run_server(mode="inline")

Python Dash resizing candlesticks

I've been trying to create a candlestick graph that shows the prices of NASDAQ and moving average on it, which has been a partial success:
import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
import yfinance as yf
import plotly.express as px
import datetime as dt
from datetime import datetime
from metody import metody
import time
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
NASDAQ = pd.read_excel(r'file.xlsx')
app = dash.Dash(external_stylesheets=external_stylesheets)
fig = go.Figure(data=go.Candlestick(
open=NASDAQ['Open'],
close=NASDAQ['Close'],
low=NASDAQ['Low'],
high=NASDAQ['High'],
))
close = NASDAQ['Close']
open = NASDAQ['Open']
srednia = metody.generateMovingAverage(NASDAQ['Close'], 3)
fig.add_trace(
go.Scatter(
y=srednia
)
)
app.layout = html.Div([
html.H1(
children="This is a chart of {}".format("NASDAQ"),
style={
'text-align': 'center'
}
),
dcc.Graph(
id='candles',
animate=True,
figure=fig,
),
dcc.Interval(
id='update',
interval=1000
)
])
app.run_server(debug=True)
unfortunately however when I'm trying to zoom the results, the candles do not upscale so that it's readable:
My question is: how do I deal with that? I'd love my chart to be nicely interactive (meaning the user can adjust the period and the candles are as big as it fits to the size of the chart).
PS: I'm really new to Dash, so if you've got any comments on my code or you know something I've done the wrong way round, please tell me :)
You need to get this into your code somewhere (upon zoom trigger):
fig.update_yaxes(range=[minY, maxY])
with minY and maxY being chosen from a downselection of your results (and rounded down and up respectively to look a bit better)
But I don't see where your zoom is being done - I assume you aren't using the plotly default but instead closing in using the lower summary bar?
You might have to dive in to the .css I'm afraid - or maybe you can insert additional lines into it before passing it to dash.Dash()

How to interact with plotly.figure_factory hover?

I tried the following code:
import plotly.io as pio
import plotly.express as px
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.figure_factory as ff
import plotly.express as px
df = px.data.carshare()
fig = go.Figure()
app = dash.Dash()
#fac figurile
fig = ff.create_hexbin_mapbox(df,lat = 'centroid_lat', lon = 'centroid_lon',nx_hexagon = 10,color = 'car_hours',
labels = {'color':'Point Count '},
opacity = 0.5)
fig.update_layout(mapbox_style="carto-darkmatter")
fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))
fig.show()
And it displays:
And I want to modify the hover so that it will only show me the float value with only the first decimal on hover and I also want to be able to display something after it displays the value. For example the value on the hover should be 'Point Count = 1019.9 cars per hour. Unfortunately, the documentation does not help very much.
It seems to me that your best option for ff.create_hexbin_mapbox would be to configure it directly through:
fig.data[0].hovertemplate = 'Point Count =%{z:,.1f}<extra>Cars per hour</extra>'
Which will turn this:
... into this:
Complete code
import plotly.io as pio
import plotly.express as px
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.figure_factory as ff
import plotly.express as px
df = px.data.carshare()
fig = go.Figure()
# app = dash.Dash()
#fac figurile
fig = ff.create_hexbin_mapbox(df,lat = 'centroid_lat', lon = 'centroid_lon',nx_hexagon = 10,color = 'car_hours',
labels = {'color':'Point Count '},
opacity = 0.5)
fig.update_layout(mapbox_style="carto-darkmatter")
fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))
fig.data[0].hovertemplate = 'Point Count =%{z:,.1f}<extra>Cars per hour</extra>'
fig.show()

Plotly xlabel and ylabel names are cropped how to make them appear full?

I was trying to create some heatmap using plotly3.10 and I encountered one problem that the
column names are not displayed full in ylabel.
import pandas as pd
import plotly.figure_factory as ff
from plotly.offline import plot, iplot, init_notebook_mode
df = pd.util.testing.makeDataFrame()
df.columns = ['this_is_long_column_name','another_column_name','yet_another_column_name','price']
df_corr = df.corr()
z = df_corr.values
fig = ff.create_annotated_heatmap(z,showscale=True,
x=df_corr.columns.values.tolist(),
y=df_corr.columns.values.tolist()
)
iplot(fig)
I got this image:
Question
How to show the full column name in ylabels?
How to show xlabel on both top and bottom with larger fontsizes?
How to show only 2 significant numbers, like df.round(2) only in plot?
Have you tried manually specifying the margins? E.g.:
import plotly.graph_objs as go
layout = go.Layout(
margin=dict(l=80, r=80, t=100, b=80)
)
This might work for you:
import numpy as np
import pandas as pd
import plotly
import plotly.offline as py
import plotly.graph_objs as go
import plotly.figure_factory as ff
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=False)
df = pd.util.testing.makeDataFrame()
df.columns = ['this_is_long_column_name','another_column_name','yet_another_column_name','price']
df_corr = df.corr()
z = df_corr.round(2).values
fig = ff.create_annotated_heatmap(z,showscale=True,
x=df_corr.columns.values.tolist(),
y=df_corr.columns.values.tolist()
)
layout = go.Layout(margin=dict(l=200, r=50, t=100, b=50))
fig.layout.update(layout)
iplot(fig)
Gives:

How to plot table and scatterplot side by side in plotly3 (not plotly4)

I have been trying to plot a table and a scatter plot side by side using plotly but to no avail for a long period. How can we do that?
How to plot table and scatter plots in plotly3.6?
I have tried this so far:
import numpy as np
import pandas as pd
import seaborn as sns
sns.set(color_codes=True)
import matplotlib.pyplot as plt
%matplotlib inline
import plotly
import plotly.offline as py
import plotly.plotly as pyp
import plotly.graph_objs as go
import plotly.figure_factory as ff
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=False)
# subplots table
fig = tls.make_subplots(rows=1, cols=2, shared_xaxes=True)
trace1 = go.Scatter(x=[1,2,3],y=[1,2,3])
df = pd.DataFrame({'name':list('ABC'),
'salary': [1000,2000,3000]})
table = ff.create_table(df)
fig.append_trace(table, 1, 2)
py.iplot(fig)
But this does not work.
However,
iplot(table) works.
How to fix the problem?
You are close but forgot the specs element. Also, you must specify positioning in .add_trace() with row=# and col=# Hope this helps.
from plotly.subplots import make_subplots
columns =['one','two']
cellValues =['first piece of data', 'second piece of data']
figure = make_subplots(
rows = 1, cols =2,
specs=[[{"type":"table"},{"type" : "scatter"}]]
)
figure.add_trace(go.Table(header=dict(
values = columns
#other elements here
),cells=dict(
values = cellValues
), row=1, col=1
)
figure.add_trace(go.Scatter(x=[1,2,3],y=[1,2,3]),row=1,col=2)
)
ff.create_table() creates a full Figure not a trace, so you can't append it to a pre-existing Figure. You'll have to go the other way and add the Scatter to the output of ff.create_table().

Categories

Resources