I am trying to overlay a point over a boxplot with Plotly and Python. I am able to add two traces to the same graph, but I couldn't find a way to make the extra point closer to the boxplot.
This is the image I get:
and the code that generates it is:
x = np.fromiter(duplicates.values(), dtype=float)
fig = go.Figure()
fig.update_layout(autosize=False, width=400, height=150, paper_bgcolor="White", plot_bgcolor='rgba(0,0,0,0)',
hovermode=False, margin=dict(l=10, r=10, b=10, t=10, pad=4),
boxmode='group', boxgroupgap=0.25,
boxgap=0.25,
)
fig.add_trace(go.Box(x=x, showlegend=False))
fig.add_trace(go.Scatter(x=np.array(duplicates[sample_id]), y=np.array(0), mode='markers', showlegend=False))
fig.update_xaxes(title='')
fig.update_yaxes(showticklabels=False)
my_div = plotly.offline.plot(fig, output_type='div',
show_link=False,
config=dict(
displayModeBar=False
))
Hi I am having trouble getting a lineplot to display properly. I have two axes and 5 line plots on one figure. The first y-axis limit cannot be set. I tried setting the range property to [0,2], however it doesn't do anything and continues to show from -2 to 4. I want the straight linear plot to overlay directly on top of the other 4 line plots and I don't know why the x-axis starts from -5. Can someone help fix the issue?
fig = go.Figure()
xs = np.linspace(0,12.5,plot_df.shape[0])
for cn in plot_df.columns:
ys = plot_df[cn].to_numpy()
fig.add_trace(go.Scatter(x=xs, y=ys,
mode='lines',
name=cn)
)
fig.add_trace(go.Scatter(x=xs, y=xs,
mode='lines',
name='mob. grad', yaxis="y2")
)
fig.update_layout(
title = "UV and Mobile phase trace of {}".format(field_dict['sample_name']),
xaxis = dict(
title = "Minutes",
domain=[0.2, 1]
),
yaxis = dict(
scaleanchor = "x",
title = "UV Abs",
range = [0,2],
position = 0.19
),
yaxis2 = dict(
title = "Mobile Phase (%)",
anchor="free",
domain=[0.1,1],
overlaying="y",
side="left",
position=0.08,
range=[0,100])
)
fig.show()
I just removed scaleanchor = "x" and it showed up properly.
I made a line graph with the code below and I'm trying to add a horizontal line at y=1. I tried following the instructions on the plotly site but it is still not showing. Does anyone know why?
date = can_tot_df.date
growth_factor = can_tot_df.growth_factor
trace0 = go.Scatter(
x=date,
y=growth_factor,
mode = 'lines',
name = 'growth_factor'
)
fig = go.Figure()
fig.add_shape(
type='line',
x0=date.min(),
y0=1,
x1=date.max(),
y1=1,
line=dict(
color='Red',
)
)
data = [trace0]
iplot(data)
Short answer, and a general solution:
fig.add_shape(type='line',
x0=0,
y0=40,
x1=8,
y1=40,
line=dict(color='Red',),
xref='x',
yref='y'
)
Details and specifics about OP's question
It's hard to tell exactly what's wrong without a sample of your data.
What I can tell for sure is that you're missing the arguments xref and yref to specify that the line is drawn as units of your y and x axis. Judging by your sample code, this is what you'd like to do since you're specifying your x-values in terms of dates.
Also, you don't need to worry about iplot for newer versions of plotly. You can display your chart just as easily by just running fig.show(). The figure and code sample below will show you how to use fig.show() and how to define your lines in terms of axis units.
Plot:
Code:
import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.add_shape(type='line',
x0=0,
y0=40,
x1=8,
y1=40,
line=dict(color='Red',),
xref='x',
yref='y'
)
fig.show()
An alternative to xref='x' is xref='paper'. Now you can specify x0 as a float between 0 and 1 spanning from the start and end of the plot.
You could also use fig.add_hline(y=1) --> see https://plotly.com/python/horizontal-vertical-shapes/
import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.add_hline(y=40, line_width=3, line_dash="dash", line_color="green")
fig.show()
If you use subplots, then this is the easiest way I found to add an other line to a subplot. this example draws a horizontal line at y=80 for all x values
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.02)
[some graph]
fig.add_trace(go.Scatter(
name='Y=80',
x = [df['date'].min(), df['date'].max()],
y = [80, 80],
mode = "lines",
marker = dict(color = 'rgba(80, 26, 80, 0.8)')
),row=1, col=1)
i found the solution on github :
df = df
fig = px.scatter(df, x="date", y="growth_factor", mode = 'lines',
hover_name=df['growth_factor'] )
fig.update_layout(shapes=[
dict(
type= 'line',
yref= 'y', y0= 1, y1= 1, # adding a horizontal line at Y = 1
xref= 'paper', x0= 0, x1= 1
)
])
fig.show()
You’re adding the line to your fig object, but fig is not getting passed into the iplot() function, only your data. So only the trace is getting plotted.
If you're using a late version of plotly, the new syntax allows you to create this plot simply using the fig object, like:
from plotly import graph_objects as go
fig = go.Figure()
# Contrived dataset for example.
x = [1, 2, 3, 4]
y = [i**2 for i in x]
fig.add_trace(go.Scatter(
x=x,
y=y,
mode = 'lines',
name = 'growth_factor'))
fig.add_shape(type='line',
x0=min(x),
y0=5,
x1=max(x),
y1=5,
line=dict(color='Red'))
fig.update_shapes(dict(xref='x', yref='y'))
fig.show()
Here are the plotly docs for convenience.
I wrote the function below to make a vertical reference line on a figure.
from plotly import graph_objects as go
import plotly.express as px
def add_vline(fig, x=0, text=None):
if text is None:
text = str(x)
fig.update_layout(
shapes=list(fig.layout.shapes) + [
go.layout.Shape(
type="line",
x0=x,
x1=x,
yref="paper",
y0=0,
y1=1,
line=dict(
color="Red",
width=2
)
)
],
annotations=list(fig.layout.annotations) + [
go.layout.Annotation(
x=x,
y=0.5,
yref="paper",
text=text
)
]
)
gapminder = px.data.gapminder()
for continent in gapminder.continent.unique():
fig = px.histogram(gapminder, x="lifeExp", title=f'Life expectancy in {continent}')
add_vline(fig, gapminder[gapminder.continent == continent].lifeExp.median())
# add_figure_to_subplot() ?
I can view these individually, but I'd like to make a report with all these generated figures shown in order. How can I either make a subplot of these figure objects, or replicate these plots within subplot traces?
I am having an issue with graph resizing due to legends when using pyplot. This is the code:
random_x = df['column1']
random_y = df['column2']
random_x1 = df['column1']
random_y1 = df['column3']
trace = go.Scatter(
x = random_x,
y = random_y,
name='abcdefghijklmnop......'
)
trace1 = go.Scatter(
x = random_x1,
y = random_y1,
name='abcdefghijklmnopadfdsfsdff......'
)
data = [trace,trace1]
iplot(data, filename='basic-line')
It gives me the graph but since my legend characters are long, it reduces the size of my actual graph. I want the legends to either come at the bottom or go further to the top
layout = go.Layout(
legend=dict(
orientation="h")
)
figure=go.Figure(data=data, layout=layout)
iplot(figure,filename='basic-line')