Animated lineplot with python plotly - python

I have gold price dataset , where first column is date on yyyy-mm-dd format and the second column is gold price.
2019-12-03 1477.60
2019-12-04 1474.45
2019-12-05 1448.40
Is there any way to make animation lineplot with python plotly where I can show gold price change along with date?

Yes, I show you an example.
The effect is fancy but you don't gain much because it is a two dimensional data, I could say indeed you are delaying the data display with no reason.
Usually animations are nice for showing 3 dimensions and obviously using the time as extra dimension to perform the animation, like the first example at plotly web animation documentation: https://plotly.com/python/animations/
import plotly.graph_objects as go
import pandas as pd
# Maybe you needed to display plot in jupyter notebook
import plotly.offline as pyo
pyo.init_notebook_mode()
# Load exmples data
dates = ["2019-12-03", "2019-12-04", "2019-12-05", "2019-12-06",
"2019-12-07", "2019-12-08", "2019-12-09"]
value_gold = [1477.60, 1474.45, 1448.40, 1447.40, 1444.40, 1449.40, 1441.40]
value_bitcoin = [1577.60, 1564.45, 1568.40, 1537.40, 1584.40, 1529.40, 1571.40]
df = pd.DataFrame(list(zip(dates, value_gold, value_bitcoin)),
columns=['date', 'value_gold', 'value_bitcoin'])
# Base plot
fig = go.Figure(
layout=go.Layout(
updatemenus=[dict(type="buttons", direction="right", x=0.9, y=1.16), ],
xaxis=dict(range=["2019-12-02", "2019-12-10"],
autorange=False, tickwidth=2,
title_text="Time"),
yaxis=dict(range=[1400, 1600],
autorange=False,
title_text="Price"),
title="Gold - Bitcoin prices evolution",
))
# Add traces
init = 1
fig.add_trace(
go.Scatter(x=df.date[:init],
y=df.value_gold[:init],
name="Gold",
visible=True,
line=dict(color="#33CFA5", dash="dash")))
fig.add_trace(
go.Scatter(x=df.date[:init],
y=df.value_bitcoin[:init],
name="Bitcoin",
visible=True,
line=dict(color="#bf00ff", dash="dash")))
# Animation
fig.update(frames=[
go.Frame(
data=[
go.Scatter(x=df.date[:k], y=df.value_gold[:k]),
go.Scatter(x=df.date[:k], y=df.value_bitcoin[:k])]
)
for k in range(init, len(df)+1)])
# Extra Formatting
fig.update_xaxes(ticks="outside", tickwidth=2, tickcolor='white', ticklen=10)
fig.update_yaxes(ticks="outside", tickwidth=2, tickcolor='white', ticklen=1)
fig.update_layout(yaxis_tickformat=',')
fig.update_layout(legend=dict(x=0, y=1.1), legend_orientation="h")
# Buttons
fig.update_layout(
updatemenus=[
dict(
buttons=list([
dict(label="Play",
method="animate",
args=[None, {"frame": {"duration": 1000}}]),
dict(label="Gold",
method="update",
args=[{"visible": [False, True]},
{"showlegend": True}]),
dict(label="Bitcoin",
method="update",
args=[{"visible": [True, False]},
{"showlegend": True}]),
dict(label="All",
method="update",
args=[{"visible": [True, True, True]},
{"showlegend": True}]),
]))])
fig.show()

Related

Plotly Scatter plot: how to create a scatter or line plot for only one group

My question might seem very easy, but I am having a difficult time understanding how to create a scatter plot or line plot for only one group of values. For example, my data frame, has 3 columns.
My table looks like the following:
fruit
lb
price
orange
1
1.4
orange
2
1.7
apple
3
2.1
apple
1
1.4
kiwi
2
1.1
I want to create a scatter plot that has the lb as the x axis and price as the y axis. However, I only want to make the plot only for the orange category. What parameter should I use to specify the orange category?
What I have now is this:
px.scatter(df, x=df.lb, y=df.price)
Adding a user selection dropdown will accomplish your goal. Use a graph object to draw a graph for each type of fruit and show the Show/Hide setting. All and only each type will be available as a type of dropdown. Give the list of Show/Hide as input for the button. Now, the drop-down selection will toggle between show and hide. Please refer to the examples in the reference.
import plotly.graph_objects as go
fig = go.Figure()
for f in df['fruit'].unique():
dff = df.query('fruit == #f')
fig.add_trace(go.Scatter(mode='markers', x=dff.lb, y=dff.price, name=f, visible=True))
fig.update_layout(
updatemenus=[
dict(
active=0,
buttons=list([
dict(label="ALL",
method="update",
args=[{"visible": [True, True, True]},
{"title": "All fruit"}]),
dict(label="Orange",
method="update",
args=[{"visible": [True, False, False]},
{"title": "Orange"}]),
dict(label="Apple",
method="update",
args=[{"visible": [False, True, False]},
{"title": "Apple"}]),
dict(label="Kiwi",
method="update",
args=[{"visible": [False, False, True]},
{"title": "Kiwi"}]),
]),
)
])
fig.show()

Scroll between multiple subplots

i have a question regarding subplots.
i’m creating plots using this command:
figure = make_subplots(
rows=4,
cols=1,
shared_xaxes=True,
subplot_titles=("title1", "title2", "title3", "title4"),
vertical_spacing=0.1,
column_titles=[
f'title'
]
)
# then creating multiple candlestick graphs like this for each row:
figure.add_trace(
go.Candlestick(
x=inner_data.index,
open=inner_data['open'],
high=inner_data['high'],
low=inner_data['low'],
close=inner_data['close'],
name=f"{ticker} - INNER GRAPH"
),
row=row,
col=1
)
figure.show()
but because i have too many rows, the plots are shrinking a lot, and i cannot see anything.
is there a way to keep the size big, and create a scroll option in the page that opens up? i have not found it anywhere in the documentation…
thanks in advance,
Yaniv
A candlestick graph has been created using four stock prices. The display area can be changed by setting the graph height. The unit is pixels. Also, the range slider is not shown as an element that makes the graph area narrower. If necessary, change it to True. Since column titles and sub-titles are covered, the column titles are not set, but are changed to the overall title.
import yfinance as yf
tickers = "AAPL TSLA GOOG NFLX"
df = yf.download(tickers, start="2021-07-01", end="2022-07-01", group_by='ticker')
df = df.stack(0).reset_index().rename(columns={'level_1':'Ticker'})
from plotly.subplots import make_subplots
import plotly.graph_objects as go
figure = make_subplots(
rows=4,
cols=1,
shared_xaxes=True,
subplot_titles=tickers.split(' '),
vertical_spacing=0.1,
# column_titles=[
# f'title'
# ]
)
for row,ticker in enumerate(tickers.split(' ')):
inner_data = df[df['Ticker'] == ticker]
figure.add_trace(
go.Candlestick(
x=inner_data.index,
open=inner_data['Open'],
high=inner_data['High'],
low=inner_data['Low'],
close=inner_data['Close'],
name=f"{ticker} - INNER GRAPH"
), row=row+1, col=1
)
figure.update_layout(title='title',
autosize=True,
height=800,
)
figure.update_xaxes(rangeslider=dict(visible=False))
figure.show()

Plotly - how to overlay two plots in same figure with slider

Aim: Having two scatter plots in the same figure while using a slider in Plotly.
Expected behavior: Show a figure with two plots updating simultaneously and sharing the same "slider step".
Current behavior: The slider steps over both scatter plots, separating them and showing one result at a time.
I attach below a minimal reproducible example adapted from the plotly documentation. Instead of simply plotting the sin(x), I also added a second plot with cos(x).
I tried using add_traces(), and also creating two separate traces and the updating them with fig = go.Figure(data=trace_list1+trace_list2) as shown here.
Any help would be much appreciated!
import plotly.graph_objects as go
import numpy as np
# Create figure
fig = go.Figure()
# Add traces, one for each slider step
for step in np.arange(0, 5, 0.5):
fig.add_traces([
go.Scatter(
x=np.arange(0, 10, 0.01),
y=np.sin(step * np.arange(0, 10, 0.01))),
go.Scatter(
x=np.arange(0, 10, 0.01),
y=np.cos(step * np.arange(0, 10, 0.01)))])
# Make 10th trace visible
fig.data[10].visible = True
# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)},
{"title": "Slider switched to step: " + str(i)}], # layout attribute
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active=10,
currentvalue={"prefix": "Frequency: "},
pad={"t": 50},
steps=steps
)]
fig.update_layout(
sliders=sliders
)
fig.show()
I enclose the answer given on the forum maintained by the Plotly community.
# Create and add slider
steps = []
for i in range(len(fig.data)):
if i % 2 == 0:
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)},
{"title": "Slider switched to step: " + str(i/2)}], # layout attribute
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
step["args"][0]["visible"][i+1] = True
steps.append(step)

Is there a way to add a button that filters data set in plotly

I'm pretty new using plotly in python. I managed to plot a box chart with my dataframe in plotly like this:
box chart
The box plot shows the entire department's performance. I wish to add a few buttons that filter or narrow down the result. For example:
Team 1 button - filter on JH, DT, MB, SC
Team 2 button - filter on NP, DH, MZ, SB
Team 3 button - filter on KT, BL, SM,LW
and so on
I read through the plotly Figure reference (https://plotly.com/python/reference/layout/updatemenus/#layout-updatemenus-items-updatemenu-buttons-items-button-args)
and managed to add the buttons with args=["Claim_Handler"] where ["Claim_Handler"] is the column name in my dataframe. However the button does not perform any action when I click on it.
Where did I do wrong?
Here is the code for the graph:
fig2 = px.box(DF2, x='Claim_Handler', y='Days_to_close',hover_data=["Claim#"])
fig2.update_layout(
title='Average days to close for Claims Closed in last 5 years',
xaxis = dict(
rangeslider = dict(
visible=True,
thickness=0.05
)
),
yaxis = dict(
),
barmode='stack',
paper_bgcolor='#FFFFFF',
showlegend=True
)
fig2.update_layout(
updatemenus=[
dict(
type = "buttons",
direction = "left",
buttons=list([
dict(
args=["Claim_Handler"],
label="DH",
method="update"
),
dict(
args=["Claim_Handler"],
label="DT",
method="update"
)
])
),]
)
fig2.show(renderer="iframe")

Python - Plotly - dynamic y-axis selection on a multiple axes plot

I have a dataframe of multiple columns, each containing a time series. I want to compare two time series plots at a time, for which I am plotting them overlayed with two y-axes as given in the example here: https://plot.ly/python/multiple-axes/#two-y-axes
My problems are:
I want plotly to let the user select only two traces at a time,
dynamically change and adjust the y-axis based on which trace is selected/un-selected
Building on the example given in the link above:
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Scatter(x=[1, 2, 3],y=[40, 50, 60],name='yaxis data')
trace2 = go.Scatter(x=[2, 3, 4],y=[4, 5, 6],name='yaxis2 data',yaxis='y2')
trace3 = go.Scatter( x=[3, 4, 5],y=[400, 500, 600],name='yaxis3 data', yaxis='y2', visible = 'legendonly')
data = [trace1, trace2, trace3]
layout = go.Layout(
title='Double Y Axis Example',
yaxis=dict(
title='yaxis title'
),
yaxis2=dict(
title='yaxis2 title',
titlefont=dict(
color='rgb(148, 103, 189)'
),
tickfont=dict(
color='rgb(148, 103, 189)'
),
overlaying='y',
side='right'
)
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig)
So plotly should let the user choose only two traces at a time to be visible on the plot, and dynamically put the next selected trace on the available y-axis side.
For example if 'yaxis data' and 'yaxis2 data' are visible, the user has to unselect either of those before selecting 'yaxis3 data' from the legends. So if the user unselects 'yaxis data' which is on the left hand side of the plot, 'yaxis3 data's y-axis labels should go on the left hand side. IF the user had unselected 'yaxis2 data', the new data would go on the right hand side.
I want the yaxis= 'y' or 'y2' to be assigned through the interactive session. I dont know how to achieve that.

Categories