Related
I have the following piece of code
import plotly.express as px
import pandas as pd
import numpy as np
x = [1,2,3,4,5,6]
df = pd.DataFrame(
{
'x': x*3,
'y': list(np.array(x)) + list(np.array(x)**2) + list(np.array(x)**.5),
'color': list(np.array(x)*0) + list(np.array(x)*0+1) + list(np.array(x)*0+2),
}
)
for plotting_function in [px.scatter, px.line]:
fig = plotting_function(
df,
x = 'x',
y = 'y',
color = 'color',
title = f'Using {plotting_function.__name__}',
)
fig.show()
which produces the following two plots:
For some reason px.line is not producing the continuous color scale that I want, and in the documentation for px.scatter I cannot find how to join the points with lines. How can I produce a plot with a continuous color scale and lines joining the points for each trace?
This is the plot I want to produce:
I am not sure this is possible using only plotly.express. If you use px.line, then you can pass the argument markers=True as described in this answer, but from the px.line documentation it doesn't look like continuous color scales are supported.
UPDATED ANSWER: in order to have both a legend that groups both the lines and markers together, it's probably simpest to use go.Scatter with the argument mode='lines+markers'. You'll need to add the traces one at a time (by plotting each unique color portion of the data one at a time) in order to be able to control each line+marker group from the legend.
When plotting these traces, you will need some functions to retrieve the colors of the lines from the continuous color scale because go.Scatter won't know what color your lines are supposed to be unless you specify them - thankfully that has been answered here.
Also you won't be able to generate a colorbar adding the markers one color at a time, so to add a colorbar, you can plot all of the markers at once using go.Scatter, but use the argument marker=dict(size=0, color="rgba(0,0,0,0)", colorscale='Plasma', colorbar=dict(thickness=20)) to display a colorbar, but ensure that these duplicate markers are not visible.
Putting all of this together:
# import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
x = [1,2,3,4,5,6]
df = pd.DataFrame(
{
'x': x*3,
'y': list(np.array(x)) + list(np.array(x)**2) + list(np.array(x)**.5),
'color': list(np.array(x)*0) + list(np.array(x)*0+1) + list(np.array(x)*0+2),
}
)
# This function allows you to retrieve colors from a continuous color scale
# by providing the name of the color scale, and the normalized location between 0 and 1
# Reference: https://stackoverflow.com/questions/62710057/access-color-from-plotly-color-scale
def get_color(colorscale_name, loc):
from _plotly_utils.basevalidators import ColorscaleValidator
# first parameter: Name of the property being validated
# second parameter: a string, doesn't really matter in our use case
cv = ColorscaleValidator("colorscale", "")
# colorscale will be a list of lists: [[loc1, "rgb1"], [loc2, "rgb2"], ...]
colorscale = cv.validate_coerce(colorscale_name)
if hasattr(loc, "__iter__"):
return [get_continuous_color(colorscale, x) for x in loc]
return get_continuous_color(colorscale, loc)
# Identical to Adam's answer
import plotly.colors
from PIL import ImageColor
def get_continuous_color(colorscale, intermed):
"""
Plotly continuous colorscales assign colors to the range [0, 1]. This function computes the intermediate
color for any value in that range.
Plotly doesn't make the colorscales directly accessible in a common format.
Some are ready to use:
colorscale = plotly.colors.PLOTLY_SCALES["Greens"]
Others are just swatches that need to be constructed into a colorscale:
viridis_colors, scale = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
colorscale = plotly.colors.make_colorscale(viridis_colors, scale=scale)
:param colorscale: A plotly continuous colorscale defined with RGB string colors.
:param intermed: value in the range [0, 1]
:return: color in rgb string format
:rtype: str
"""
if len(colorscale) < 1:
raise ValueError("colorscale must have at least one color")
hex_to_rgb = lambda c: "rgb" + str(ImageColor.getcolor(c, "RGB"))
if intermed <= 0 or len(colorscale) == 1:
c = colorscale[0][1]
return c if c[0] != "#" else hex_to_rgb(c)
if intermed >= 1:
c = colorscale[-1][1]
return c if c[0] != "#" else hex_to_rgb(c)
for cutoff, color in colorscale:
if intermed > cutoff:
low_cutoff, low_color = cutoff, color
else:
high_cutoff, high_color = cutoff, color
break
if (low_color[0] == "#") or (high_color[0] == "#"):
# some color scale names (such as cividis) returns:
# [[loc1, "hex1"], [loc2, "hex2"], ...]
low_color = hex_to_rgb(low_color)
high_color = hex_to_rgb(high_color)
return plotly.colors.find_intermediate_color(
lowcolor=low_color,
highcolor=high_color,
intermed=((intermed - low_cutoff) / (high_cutoff - low_cutoff)),
colortype="rgb",
)
fig = go.Figure()
## add the lines+markers
for color_val in df.color.unique():
color_val_normalized = (color_val - min(df.color)) / (max(df.color) - min(df.color))
# print(f"color_val={color_val}, color_val_normalized={color_val_normalized}")
df_subset = df[df['color'] == color_val]
fig.add_trace(go.Scatter(
x=df_subset['x'],
y=df_subset['y'],
mode='lines+markers',
marker=dict(color=get_color('Plasma', color_val_normalized)),
name=f"line+marker {color_val}",
legendgroup=f"line+marker {color_val}"
))
## add invisible markers to display the colorbar without displaying the markers
fig.add_trace(go.Scatter(
x=df['x'],
y=df['y'],
mode='markers',
marker=dict(
size=0,
color="rgba(0,0,0,0)",
colorscale='Plasma',
cmin=min(df.color),
cmax=max(df.color),
colorbar=dict(thickness=40)
),
showlegend=False
))
fig.update_layout(
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01),
yaxis_range=[min(df.y)-2,max(df.y)+2]
)
fig.show()
You can achieve this using only 2 more parameters in px.line:
markers=True
color_discrete_sequence=my_plotly_continuous_sequence
The complete code would look something like this (Note the list slicing [::4] so that the colors are well spaced):
import plotly.express as px
import pandas as pd
import numpy as np
x = [1, 2, 3, 4, 5, 6]
df = pd.DataFrame(
{
'x': x * 3,
'y': list(np.array(x)) + list(np.array(x) ** 2) + list(np.array(x) ** .5),
'color': list(np.array(x) * 0) + list(np.array(x) * 0 + 1) + list(np.array(x) * 0 + 2),
}
)
fig = px.line(
df,
x='x',
y='y',
color='color',
color_discrete_sequence=px.colors.sequential.Plasma[::4],
markers=True,
template='plotly'
)
fig.show()
This produces the following output.
In case you have more lines than the colors present in the colormap, you can construct a custom colorscale so that you get one complete sequence instead of a cycling sequence:
rgb = px.colors.convert_colors_to_same_type(px.colors.sequential.RdBu)[0]
colorscale = []
n_steps = 4 # Control the number of colors in the final colorscale
for i in range(len(rgb) - 1):
for step in np.linspace(0, 1, n_steps):
colorscale.append(px.colors.find_intermediate_color(rgb[i], rgb[i + 1], step, colortype='rgb'))
fig = px.line(df_e, x='temperature', y='probability', color='year', color_discrete_sequence=colorscale, height=900)
fig.show()
this is my first foray into Plotly. I love the ease of use compared to matplotlib and bokeh. However I'm stuck on some basic questions on how to beautify my plot. First, this is the code below (its fully functional, just copy and paste!):
import plotly.express as px
from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools
d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
'Current': [15,9,20,10,20,8,10,21,18,14],
'Goal': [50,35,21,44,20,24,14,29,28,19]
}
dataset = pd.DataFrame(d)
grouped = dataset.groupby('Category', as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']
fig1 = px.bar(dataset, x = v_current, y = v_cat, orientation = 'h',
color_discrete_sequence = ["#ff0000"],height=10)
fig2 = px.bar(dataset, x = v_goal, y = v_cat, orientation = 'h',height=15)
trace1 = fig1['data'][0]
trace2 = fig2['data'][0]
fig = make_subplots(rows = 1, cols = 1, shared_xaxes=True, shared_yaxes=True)
fig.add_trace(trace2, 1, 1)
fig.add_trace(trace1, 1, 1)
fig.update_layout(barmode = 'overlay')
fig.show()
Here is the Output:
Question1: how do I make the width of v_current (shown in red bar) smaller? As in, it should be smaller in height since this is a horizontal bar. I added the height as 10 for trace1 and 15 for trace2, but they are still showing at the same heights.
Question2: Is there a way to make the v_goal (shown in blue bar) only show it's right edge, instead of a filled out bar? Something like this:
If you noticed, I also added a line under each of the category. Is there a quick way to add this as well? Not a deal breaker, just a bonus. Other things I'm trying to do is add animation, etc but that's for some other time!
Thanks in advance for answering!
Running plotly.express wil return a plotly.graph_objs._figure.Figure object. The same goes for plotly.graph_objects running go.Figure() together with, for example, go.Bar(). So after building a figure using plotly express, you can add lines or traces through references directly to the figure, like:
fig['data'][0].width = 0.4
Which is exactly what you need to set the width of your bars. And you can easily use this in combination with plotly express:
Code 1
fig = px.bar(grouped, y='Category', x = ['Current'],
orientation = 'h', barmode='overlay', opacity = 1,
color_discrete_sequence = px.colors.qualitative.Plotly[1:])
fig['data'][0].width = 0.4
Plot 1
In order to get the bars or shapes to indicate the goal levels, you can use the approach described by DerekO, or you can use:
for i, g in enumerate(grouped.Goal):
fig.add_shape(type="rect",
x0=g+1, y0=grouped.Category[i], x1=g, y1=grouped.Category[i],
line=dict(color='#636EFA', width = 28))
Complete code:
import plotly.express as px
from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools
d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
'Current': [15,9,20,10,20,8,10,21,18,14],
'Goal': [50,35,21,44,20,24,14,29,28,19]
}
dataset = pd.DataFrame(d)
grouped = dataset.groupby('Category', as_index=False).sum()
fig = px.bar(grouped, y='Category', x = ['Current'],
orientation = 'h', barmode='overlay', opacity = 1,
color_discrete_sequence = px.colors.qualitative.Plotly[1:])
fig['data'][0].width = 0.4
fig['data'][0].marker.line.width = 0
for i, g in enumerate(grouped.Goal):
fig.add_shape(type="rect",
x0=g+1, y0=grouped.Category[i], x1=g, y1=grouped.Category[i],
line=dict(color='#636EFA', width = 28))
f = fig.full_figure_for_development(warn=False)
fig.show()
You can use Plotly Express and then directly access the figure object as #vestland described, but personally I prefer to use graph_objects to make all of the changes in one place.
I'll also point out that since you are stacking bars in one chart, you don't need subplots. You can create a graph_object with fig = go.Figure() and add traces to get stacked bars, similar to what you already did.
For question 1, if you are using go.Bar(), you can pass a width parameter. However, this is in units of the position axis, and since your y-axis is categorical, width=1 will fill the entire category, so I have chosen width=0.25 for the red bar, and width=0.3 (slightly larger) for the blue bar since that seems like it was your intention.
For question 2, the only thing that comes to mind is a hack. Split the bars into two sections (one with height = original height - 1), and set its opacity to 0 so that it is transparent. Then place down bars of height 1 on top of the transparent bars.
If you don't want the traces to show up in the legend, you can set this individually for each bar by passing showlegend=False to fig.add_trace, or hide the legend entirely by passing showlegend=False to the fig.update_layout method.
import plotly.express as px
import plotly.graph_objects as go
# from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools
d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
'Current': [15,9,20,10,20,8,10,21,18,14],
'Goal': [50,35,21,44,20,24,14,29,28,19]
}
dataset = pd.DataFrame(d)
grouped = dataset.groupby('Category', as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']
fig = go.Figure()
## you have a categorical plot and the units for width are in position axis units
## therefore width = 1 will take up the entire allotted space
## a width value of less than 1 will be the fraction of the allotted space
fig.add_trace(go.Bar(
x=v_current,
y=v_cat,
marker_color="#ff0000",
orientation='h',
width=0.25
))
## you can show the right edge of the bar by splitting it into two bars
## with the majority of the bar being transparent (opacity set to 0)
fig.add_trace(go.Bar(
x=v_goal-1,
y=v_cat,
marker_color="#ffffff",
opacity=0,
orientation='h',
width=0.30,
))
fig.add_trace(go.Bar(
x=[1]*len(v_cat),
y=v_cat,
marker_color="#1f77b4",
orientation='h',
width=0.30,
))
fig.update_layout(barmode='relative')
fig.show()
I use plotly package to show dynamic finance chart at python. However I didn't manage to put my all key points lines on one chart with for loop. Here is my code:
fig.update_layout(
for i in range(0,len(data)):
shapes=[
go.layout.Shape(
type="rect",
x0=data['Date'][i],
y0=data['Max_alt'][i],
x1='2019-12-31',
y1=data['Max_ust'][i],
fillcolor="LightSkyBlue",
opacity=0.5,
layer="below",
line_width=0)])
fig.show()
I have a data like below one. It is time series based EURUSD parity financial dataset. I calculated two constraits for both Local Min and Max. I wanted to draw rectangule shape to based on for each Min_alt / Min_ust and Max_alt / Max_range. I can draw for just one date like below image however I didn't manage to show all ranges in same plotly graph.
Here is the sample data set.
Here is the solution for added lines:
import datetime
colors = ["LightSkyBlue", "RoyalBlue", "forestgreen", "lightseagreen"]
ply_shapes = {}
for i in range(0, len(data1)):
ply_shapes['shape_' + str(i)]=go.layout.Shape(type="rect",
x0=data1['Date'][i].strftime('%Y-%m-%d'),
y0=data1['Max_alt'][i],
x1='2019-12-31',
y1=data1['Max_ust'][i],
fillcolor="LightSkyBlue",
opacity=0.5,
layer="below"
)
lst_shapes=list(ply_shapes.values())
fig1.update_layout(shapes=lst_shapes)
fig1.show()
However I have still problems to add traces to those lines. I mean text attribute.
Here is my code:
add_trace = {}
for i in range(0, len(data1)):
add_trace['scatter_' + str(i)] = go.Scatter(
x=['2019-12-31'],
y=[data1['Max_ust'][i]],
text=[str(data['Max_Label'][i])],
mode="text")
lst_trace = list(add_trace.values())
fig2=go.Figure(lst_trace)
fig2.show()
The answer:
For full control of each and every shape you insert, you could follow this logic:
fig = go.Figure()
#[...] data, traces and such
ply_shapes = {}
for i in range(1, len(df)):
ply_shapes['shape_' + str(i)]=go.layout.Shape()
lst_shapes=list(ply_shapes.values())
fig.update_layout(shapes=lst_shapes)
fig.show()
The details:
I'm not 100% sure what you're aimin to do here, but the following suggestion will answer your question quite literally regarding:
How to add more than one shape with loop in plotly?
Then you'll have to figure out the details regarding:
manage to put my all key points lines on one chart
Plot:
The plot itself is most likely not what you're looking for, but since you for some reason are adding a plot by the length of your data for i in range(0,len(data), I've made this:
Code:
This snippet will show how to handle all desired traces and shapes with for loops:
# Imports
import pandas as pd
#import matplotlib.pyplot as plt
import numpy as np
import plotly.graph_objects as go
#from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
# data, random sample to illustrate stocks
np.random.seed(12345)
rows = 20
x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum()
y = pd.Series(x-np.random.randn(rows)*5,index=pd.date_range('1/1/2020', periods=rows))
df = pd.concat([y,x], axis = 1)
df.columns = ['StockA', 'StockB']
# lines
df['keyPoints1']=np.random.randint(-5,5,len(df))
df['keyPoints2']=df['keyPoints1']*-1
# plotly traces
fig = go.Figure()
stocks = ['StockA', 'StockB']
df[stocks].tail()
traces = {}
for i in range(0, len(stocks)):
traces['trace_' + str(i)]=go.Scatter(x=df.index,
y=df[stocks[i]].values,
name=stocks[i])
data=list(traces.values())
fig=go.Figure(data)
# shapes update
colors = ["LightSkyBlue", "RoyalBlue", "forestgreen", "lightseagreen"]
ply_shapes = {}
for i in range(1, len(df)):
ply_shapes['shape_' + str(i)]=go.layout.Shape(type="line",
x0=df.index[i-1],
y0=df['keyPoints1'].iloc[i-1],
x1=df.index[i],
y1=df['keyPoints2'].iloc[i-1],
line=dict(
color=np.random.choice(colors,1)[0],
width=30),
opacity=0.5,
layer="below"
)
lst_shapes=list(ply_shapes.values())
fig.update_layout(shapes=lst_shapes)
fig.show()
Also you can use fig.add_{shape}:
fig = go.Figure()
fig.add_trace(
go.Scatter( ...)
for i in range( 1, len( vrect)):
fig.add_vrect(
x0=vrect.start.iloc[ i-1],
x1=vrect.finish.iloc[ i-1],
fillcolor=vrect.color.iloc[ i-1]],
opacity=0.25,
line_width=0)
fig.show()
In Plotly (Python), box plots detect outlier by default, and if there are what it decides to be outliers, the whiskers are not extended to the outliers. However, I know that none of my data points should be treated as outliers. Is it possible to turn off outlier detection in box plots, and have the whole dataset treated as inliers?
By the way, I still want to show all of the points next to the box plots, so I don't want to use the option boxpoints=False to force the box plot to include all points.
It seems that the only way to do this at the time being is to use mutliple traces and adjust them to the same position like the plot and snippet below will show. If you'd like some details, take a look at the snippets and plots at the end.
In the following snippet, I'm using go.Box(x=x0) for two different traces with the same data but different settings for the markers and lines to achieve this:
Plot:
Code:
# imports
import plotly
from plotly import tools
import pandas as pd
import numpy as np
import plotly.graph_objs as go
# setup
np.random.seed(123)
# data
y0 = np.random.randn(50)-1
x0 = y0
x0 = [0 for y in y0]
# include an outlier
y0[-1] = 4
# traces
trace0 = go.Box(x=x0,
y=y0, boxpoints = False, pointpos = 0,
marker = dict(color = 'rgb(66, 167, 244)'),
)
trace1 = go.Box(x=x0,
y=y0, boxpoints = 'all', pointpos = 0,
marker = dict(color = 'rgb(66, 66, 244)'),
line = dict(color = 'rgba(0,0,0,0)'),
fillcolor = 'rgba(0,0,0,0)'
)
data=[trace0, trace1]
# figure
fig = go.Figure(data)
fig.show()
Details about the default behaviour:
If Boxpoints are not specifed, the lines will not include the outlier:
Plot: Default
Code:
# imports
import plotly
from plotly import tools
import pandas as pd
import numpy as np
import plotly.graph_objs as go
# setup
np.random.seed(123)
# data
y0 = np.random.randn(50)-1
y0[-1] = 4
# traces
trace0 = go.Box(y=y0, pointpos = 0,
marker = dict(color = 'rgb(66, 167, 244)'),
)
# figure
fig = go.Figure(trace0)
fig.show()
The only way you can make the lines inlcude the outlier, is to remove all boxpoints by setting boxpoints = False
Plot:
Code:
# imports
import plotly
from plotly import tools
import pandas as pd
import numpy as np
import plotly.graph_objs as go
# setup
np.random.seed(123)
# data
y0 = np.random.randn(50)-1
y0[-1] = 4
# traces
trace0 = go.Box(y=y0, pointpos = 0,
marker = dict(color = 'rgb(66, 167, 244)'),
boxpoints = False
)
# figure
fig = go.Figure(trace0)
fig.show()
And of course, this is not what you're aiming to do.
I hope this was helpful. If not, then don't hesitate to let me know.
python 3.6 latest plotly used :
The python Graph is created using plotly offline/Online function where three different dataframe inputs are used for y axis plotting and x axis are shared (In general it is Date index). The graphs are perfectly fine.
Only active area data on current layout's graph shown for the particular subplot layout, I want all the three layout data display when hovering the mouse in any layout.How to achieve this ?
eq_high = go.Scatter(
x=df.index,
y=df['High'],
name = "EQHigh",
line = dict(color = '#3EBF06'),
opacity = 0.8)
eq_low = go.Scatter(
x=df.index,
y=df['Low'],
name = "EQLow",
line = dict(color = '#FD2D00'),
opacity = 0.8)
##
op_high_ce = go.Scatter(
x=stock_opt_ce.index,
y=stock_opt_ce['High'],
name = "OpHighCE",
line = dict(color = '#15655F'),
opacity = 0.8)
op_low_ce = go.Scatter(
x=stock_opt_ce.index,
y=stock_opt_ce['Low'],
name = "OpLowCE",
line = dict(color = '#0D7B7F'),
opacity = 0.8)
op_last_ce = go.Scatter(
x=stock_opt_ce.index,
y=stock_opt_ce['Last'],
name = "OpLastCE",
line = dict(color = '#6AA6A2'),
opacity = 0.8)
op_settlePr_ce = go.Scatter(
x=stock_opt_ce.index,
y=stock_opt_ce['Settle Price'],
name = "OpSettlePrCE",
line = dict(color = '#2AADD1'),
opacity = 0.8)
##
op_high_pe = go.Scatter(
x=stock_opt_pe.index,
y=stock_opt_pe['High'],
name = "OpHighPE",
line = dict(color = '#FA6300'),
opacity = 0.8)
op_low_pe = go.Scatter(
x=stock_opt_pe.index,
y=stock_opt_pe['Low'],
name = "OpLowPE",
line = dict(color = '#AC4C0D'),
opacity = 0.8)
op_last_pe = go.Scatter(
x=stock_opt_pe.index,
y=stock_opt_pe['Last'],
name = "OpLastPE",
line = dict(color = '#E19B6D'),
opacity = 0.8)
op_settlepr_pe = go.Scatter(
x=stock_opt_pe.index,
y=stock_opt_pe['Low'],
name = "OpSettlePrPE",
line = dict(color = '#A54E1F'),
opacity = 0.8)
data = [eq_high,eq_low,op_high_ce,op_low_ce,op_settlePr_ce,op_high_pe,op_low_pe,op_settlepr_pe]
#custome Date Range plotting
layout = dict(
title = "Graph",
xaxis = dict(
range = ['2017-10-1','2017-11-27'])
)
fig = dict(data=data, layout=layout)
iplot(fig, filename = "CorrelationOfEquityAndOptionData")
plot(fig,show_link = False)
1.what changes to be made in the above code to show all three layout data values while mouse hovering.currently it shows only one layout graph values.
2.How to show the graph data points on right side or top side or bottom side or left side ,rather than showing the graph data onto the graph.
3.Any better optimized way of doing this.
Expected result:
This answer has been heavily edited after a brief discussion in the comments
Question 1:
After various attempts it seems that this is not possible at the moment. There is however an issue on github:
They would like hover labels to appear on all traces across all y-axes
with shared x-axes. Right now, they only appear in the subplot that
you are hovering in.
Question 2:
To alter the way the hoverinfo is displayed, use fig['layout']['hovermode']. The problem here is that your options are limited to one of the following: 'x', 'y', or 'closest'. And if you click the Compare data on hover option, there's no way to set it back to fig['layout']['hovermode'] = 'y' without running your code again. You can also change the way information is displayed for each series using fig['data'][ser]['hoverinfo']= 'all'. Here, you can insert multiple options like x or x+y in a list.
Heres an example with some random data:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# setup
init_notebook_mode(connected=True)
# data
np.random.seed(1)
x = np.linspace(0, 1, 50)
y1 = np.cumsum(np.random.randn(50))
y0 = np.cumsum(np.random.randn(50))
# Data
trace0 = go.Scatter(
x=x,
y=y0,
)
trace1 = go.Scatter(
x=x,
y=y1,
)
# layout
layout = go.Layout(yaxis=dict(range=[-10,10])
)
# Plot
fig = go.Figure(data=[trace0, trace1], layout=layout)
# Edit hoveroptions
fig['layout']['hovermode'] = 'y'
for ser in range(0,len(fig['data'])):
fig['data'][ser]['hoverinfo']= 'all'
iplot(fig)
Question 3:
Im sorry to say that I don't know any other optimized way to do this.
Question 1:
The easiest way is to plot all 3 charts on a single chart by using subplots. Below is basic code to make subplots and obtain all hover information.
from plotly.subplots import make_subplots
fig=make_subplots(rows=3, cols=1, shared_xaxes=True)
fig.update_layout(hovermode='x unified')
Use the above mentioned parameters along with the others that you might need.
Question 2:
I have been searching a way to reach same outcome but haven't been successful yet.
If you find the answer please let me know.