Plotly Outputting Blank Plot in Jupyter Lab - python

I have the following code in a Jupyter Lab cell:
import investpy
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np
search_result = investpy.search_quotes(
text='EXPO',
countries=['Sri Lanka'],
products=['stocks'],
n_results=1)
df = search_result.retrieve_historical_data(
from_date='01/01/2000',
to_date='21/04/2021')
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.,
specs=[[{'type':'candlestick'}],[{'type':'bar'}]])
fig.add_trace(go.Candlestick(x=df.index,
open=df.loc[:, 'Open'],
high=df.loc[:, 'High'],
low=df.loc[:, 'Low'],
close=df.loc[:, 'Close']), row=1, col=1)
fig.add_trace(go.Bar(x=df.index, y=df.loc[:, 'Volume']), row=2, col=1)
fig.update_layout(height=600, width=600, title_text="EXPO.N0000")
fig.show()
I don't get an error message but I get a blank output. I am trying plot price Candlestick with volume.
When I try the same on Jupyter Notebook it works.

Related

plotly.express.timeline in subplots

Using Timelines with plotly.express, I can get a working Gantt Chart:
import plotly.express as px
import pandas as pd
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
fig.show()
Following advice from here, I try to add it to a subplot with shared_xaxes = True
from plotly.subplots import make_subplots
fig_sub = make_subplots(rows=2, shared_xaxes=True)
fig_sub.append_trace(fig['data'][0], row=1, col=1)
fig_sub.append_trace(fig['data'][0], row=2, col=1)
fig_sub.show()
But it treats it like a graph_objects and doesn't display a Gantt chart.
Does anyone have any workarounds or suggestionts?
It is unclear why this is the case, but it appears that the date has been de-formatted, so once again, setting the date in the x-axis format will restore the timeline.
from plotly.subplots import make_subplots
fig_sub = make_subplots(rows=2, shared_xaxes=True)
fig_sub.append_trace(fig['data'][0], row=1, col=1)
fig_sub.append_trace(fig['data'][0], row=2, col=1)
fig_sub.update_xaxes(type='date')
fig_sub.show()

In Python, how can I update plotly figures using 'update_annotations'?

I am using Plotly in python to generate figures. As in the title, I cannot update figure annotations with the update_annotations function.
The following is an example of multiplot.
data = pd.DataFrame(np.random.rand(10,3), columns=['A', 'B', 'C'], index=pd.date_range(start='2001-01-01', periods=10))
fig = make_subplots(rows=3, cols=1, subplot_titles=['Top','Middle', 'Bottom'])
fig.add_trace(go.Scatter(x=data.index, y=data['A'], mode='lines'), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['B'], mode='lines'), row=2, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['C'], mode='lines'), row=3, col=1)
I can change the name of the top figure from 'TOP' to 'TOP_TEST' and its position with the following code.
fig['layout']['annotations'][0]['text'] = 'TOP_TEST'
fig['layout']['annotations'][0]['x'] = 0.02
However, I do not understand why I cannot do the same with the function update_annotations. If it works, it seems to be much easier to change multiple parameters at once.
fig.update_annotations(row=1, col=1, text='TOP_TEST', x=0.02)
Thank you for any comment in advance.
have looked into plotly code. update_annotations() uses _select_annotations_like()
whenever you specify row or col parameters the internal method returns effectively an empty list. Code gets a bit more challenging to follow after that. This appears to be a bug
as a work around you can use update_annotations() with selector parameter. Demonstrated in code below
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
data = pd.DataFrame(np.random.rand(10,3), columns=['A', 'B', 'C'], index=pd.date_range(start='2001-01-01', periods=10))
fig = make_subplots(rows=3, cols=1, subplot_titles=['Top','Middle', 'Bottom'])
fig.add_trace(go.Scatter(x=data.index, y=data['A'], mode='lines'), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['B'], mode='lines'), row=2, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['C'], mode='lines'), row=3, col=1)
# empty so nothing to update...
list(fig._select_annotations_like(prop="annotations", row=1, col=1))
# select based on text on we're ok
fig.update_annotations(selector={"text":"Top"}, text="TOP_TEST", x=.02)

Python Plotly adding px objects to a subplot object

So I'm trying to combine two plots into one. I've made these plots with the plotly.express library rather than the plotly.graphs_objs.
Now, plotly suggests using: fig = make_subplots(rows=3, cols=1) and then append_trace or add_trace
However, this doesn't work for express objects since the append trace expects a single. trace. How can I add a express figure to a subplot? Or is this simply not possible. One option I've tried was fig.data[0] but this will only add the first line/data entry. Rn my code looks like:
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
histo_phases = phases_distribution(match_file_, range)
fig = px.line(match_file,
x="Minutes", y=["Communicatie", 'Gemiddelde'], color='OPPONENT')
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " + str(range) + "minuten",
legend_title='Tegenstander',
)
double_plot.append_trace(fig.data, row=1, col=1)
double_plot.append_trace(histo_phases.data, row=2, col=1)
Thanks in advance.
your code sample does not include creation of data frames and figures. Have simulated
it is as simple as adding each traces from figures created with plotly express to figure created with make_subplots()
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
full code
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
import numpy as np
df = px.data.tips()
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
# histo_phases = phases_distribution(match_file_, range)
histo_phases = px.histogram(df, x="total_bill")
match_file = pd.DataFrame(
{
"Minutes": np.repeat(range(60), 10),
"Communicatie": np.random.uniform(1, 3, 600),
"Gemiddelde": np.random.uniform(3, 5, 600),
"OPPONENT": np.tile(list("ABCDEF"), 100),
}
)
fig = px.line(match_file, x="Minutes", y=["Communicatie", "Gemiddelde"], color="OPPONENT")
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " + str(range) + "minuten",
legend_title="Tegenstander",
)
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
double_plot

Is it possible to create a subplot with Plotly Express?

I would like to create a subplot with 2 plot generated with the function plotly.express.line, is it possible? Given the 2 plot:
fig1 =px.line(df, x=df.index, y='average')
fig1.show()
fig2 = px.line(df, x=df.index, y='Volume')
fig2.show()
I would like to generate an unique plot formed by 2 subplot (in the example fig1 and fig2)
Yes, you can build subplots using plotly express. Either
1. directly through the arguments facet_row and facet_colums (in which case we often talk about facet plots, but they're the same thing), or
2. indirectly through "stealing" elements from figures built with plotly express and using them in a standard make_subplots() setup with fig.add_traces()
Method 1: Facet and Trellis Plots in Python
Although plotly.express supports data of both wide and long format, I often prefer building facet plots from the latter. If you have a dataset such as this:
Date variable value
0 2019-11-04 average 4
1 2019-11-04 average 2
.
.
8 2019-12-30 volume 5
9 2019-12-30 volume 2
then you can build your subplots through:
fig = px.line(df, x='Date', y = 'value', facet_row = 'variable')
Plot 1:
By default, px.line() will apply the same color to both lines, but you can easily handle that through:
fig.update_traces(line_color)
This complete snippet shows you how:
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
df = pd.DataFrame({'Date': ['2019-11-04', '2019-11-04', '2019-11-18', '2019-11-18', '2019-12-16', '2019-12-16', '2019-12-30', '2019-12-30'],
'variable':['average', 'volume', 'average', 'volume', 'average','volume','average','volume'],
'value': [4,2,6,5,6,7,5,2]})
fig = px.line(df, x='Date', y = 'value', facet_row = 'variable')
fig.update_traces(line_color = 'red', row = 2)
fig.show()
Method 2: make_subplots
Since plotly express can do some pretty amazing stuff with fairly complicated datasets, I see no reason why you should not stumple upon cases where you would like to use elements of a plotly express figure as a source for a subplot. And that is very possible.
Below is an example where I've built to plotly express figures using px.line on the px.data.stocks() dataset. Then I go on to extract some elements of interest using add_trace and go.Scatter in a For Loop to build a subplot setup. You could certainly argue that you could just as easily do this directly on the data source. But then again, as initially stated, plotly express can be an excellent data handler in itself.
Plot 2: Subplots using plotly express figures as source:
Complete code:
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
df = px.data.stocks().set_index('date')
fig1 = px.line(df[['GOOG', 'AAPL']])
fig2 = px.line(df[['AMZN', 'MSFT']])
fig = make_subplots(rows=2, cols=1)
for d in fig1.data:
fig.add_trace((go.Scatter(x=d['x'], y=d['y'], name = d['name'])), row=1, col=1)
for d in fig2.data:
fig.add_trace((go.Scatter(x=d['x'], y=d['y'], name = d['name'])), row=2, col=1)
fig.show()
There is no need to use graph_objects module if you have just already generated px figures for making subplots. Here is the full code.
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
df = px.data.stocks().set_index('date')
fig1 = px.line(df[['GOOG', 'AAPL']])
fig2 = px.line(df[['AMZN', 'MSFT']])
fig = make_subplots(rows=2, cols=1)
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig1['data'][1], row=1, col=1)
fig.add_trace(fig2['data'][0], row=2, col=1)
fig.add_trace(fig2['data'][1], row=2, col=1)
fig.show()
If there are more than two variables in each plot, one can use for loop also to add the traces using fig.add_trace method.
From the documentation, Plotly express does not support arbitrary subplot capabilities. You can instead use graph objects and traces (note that go.Scatter is equivalent):
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
## create some random data
df = pd.DataFrame(
data={'average':[1,2,3], 'Volume':[7,3,6]},
index=['a','b','c']
)
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
go.Scatter(x=df.index, y=df.average, name='average'),
row=1, col=1
)
fig.add_trace(
go.Scatter(x=df.index, y=df.Volume, name='Volume'),
row=1, col=2
)
fig.show()

How can I change the X axis of my plotly graph to represent the dates stored as row headers in my pandas dataframe? Python For Finance Cookbook 2020

I am going through the book 'Python For Finance Cookbook' written in 2020 published by Packt. In ch 1, plotly is used to graph stock price, return and log returns. However plotly updated their documentation right after the publication of the book so I am having a hard time replicating the plot. Here is the link to the repo https://github.com/erykml/Python-for-Finance-Cookbook/tree/master/Chapter%2001 . I want to plot 3 line graphs on top of one another using the same x axis, which would be the date. I got this, but i cant change the x axis to reflect the year, it is stuck on counting number of days from 1990 to 2020. Thank you.
import pandas as pd
import yfinance as yf
import numpy as np
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
init_notebook_mode()
df = yf.download('MSFT', auto_adjust = False, progress=False)
df = df.loc[:, ['Adj Close']]
df.rename(columns={'Adj Close': 'adj_close'}, inplace=True)
df['simple_rtn'] = df.adj_close.pct_change()
df['log_rtn'] = np.log(df.adj_close / df.adj_close.shift(1))
df.dropna(how = 'any', inplace = True)
px.line(data_frame=df, title='MSFT time series')
fig = make_subplots(rows=3, cols=1,
shared_xaxes=True,
vertical_spacing=0.02)
fig.add_trace(go.Scatter(y = df['adj_close']),
row=1, col=1)
fig.add_trace(go.Scatter(y = df['simple_rtn']),
row=2, col=1)
fig.add_trace(go.Scatter(y = df['log_rtn']),
row=3, col=1)
I got it, lol very simple fix. I just set x=df.index

Categories

Resources