How to add an extra point over a boxplot graph with plotly? - python

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
))

Related

How to horizontally orient a bar plot in plotly using python?

I have a bar plot that resembles this something like this-
import plotly.graph_objects as go
months = ["ABC","XYZ"]
fig = go.Figure()
fig.add_trace(go.Bar(
x=months,
y=[3.95,4.04],
name='SMD',
marker_color='yellow'
))
fig.add_trace(go.Bar(
x=months,
y=[3.78,4.06],
name='Camrest',
marker_color='black'
))
fig.add_trace(go.Bar(
x=months,
y=[4.16,4.28],
name='MWOZ 2.1',
marker_color='cadetblue'
))
fig.update_layout(barmode='group', template="plotly_white")
fig.show()
I would like to anti-clockwise rotate the bar plot by 45 degrees, that is, horizontally orient the bar graph. How can I achieve this?
Also, how can I add a custom label to the y-axis as it currently only has the number scale and no axis name?
A horizontal bar graph can be created by reversing the x- and y-axes of a normal bar graph and specifying the graph direction. In addition, the y-axis is reversed. Refer to this in the official reference.
import plotly.graph_objects as go
months = ["ABC","XYZ"]
fig = go.Figure()
fig.add_trace(go.Bar(
y=months,
x=[3.95,4.04],
name='SMD',
marker_color='yellow',
orientation='h'
))
fig.add_trace(go.Bar(
y=months,
x=[3.78,4.06],
name='Camrest',
marker_color='black',
orientation='h'
))
fig.add_trace(go.Bar(
y=months,
x=[4.16,4.28],
name='MWOZ 2.1',
marker_color='cadetblue',
orientation='h'
))
fig.update_layout(barmode='group', template="plotly_white", yaxis=dict(autorange='reversed'))
fig.show()

How to get bar colors of multiple traces from bar chart?

I created a bar chart with multiple traces using a loop. The colors of each trace are assigned by plotly automatically. Now chart is done, how to get colors of all traces? I needed to assign these same colors to another scatter plot inside subplots to make color consistent. Thank you so much for your help.
for i in range (10):
fig.add_trace(
go.Bar(
x=weights_df_best.index,
y=weights_df_best[col].values,
name = col,
text=col,
hoverinfo='text',
legendgroup = '1',
offsetgroup=0,
),
row=1,
col=1,
)
If you'd like to put the colors in a list after you've produced a figure, just run:
colors = []
fig.for_each_trace(lambda t: colors.append(t.marker.color))
If you use that approach in the complete snippet below, you'll get
['#636efa', '#EF553B', '#00cc96']
Plot
Complete code:
import plotly.express as px
df = px.data.medals_long()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
colors = []
fig.for_each_trace(lambda t: colors.append(t.marker.color))
colors

Convert plotly marker from continuous to discrete

Following is my input file i'm trying to display on a map using plotly.
data.csv
lat,long,type
-7.80715,110.371203,1
-7.791087,110.368346,3
-7.778744,110.365107,7
-7.77877,110.365379,4
The script works but the scale is displayed in a continuous format. I tried to convert the column type to text as mentioned here but I couldn't get it to work. Is there a easier way to fix this problem?
df = pd.read_csv("data.csv").dropna()
fig = go.Figure(go.Scattermapbox(
lat=df["lat"].tolist(),
lon=df["long"].tolist(),
mode='markers',
text=df['type'].tolist(),
marker=go.scattermapbox.Marker(
size=10,
color=df['type'],
showscale=True
),
))
fig.show()
If you want to specify a discrete color, you can either deal with it directly as a list of color specifications, or you can specify the default color name in plotly_express.
import plotly.graph_objects as go
import plotly.express as px
mapbox_access_token = open("mapbox_api_key.txt").read()
colors = px.colors.qualitative.D3
fig = go.Figure(go.Scattermapbox(
lat=df["lat"].tolist(),
lon=df["long"].tolist(),
mode='markers',
text=df['type'].tolist(),
marker=go.scattermapbox.Marker(
size=10,
color=colors,
showscale=False
),
))
fig.update_layout(
autosize=False,
height=450,
width=1000,
mapbox=dict(
accesstoken=mapbox_access_token,
style="outdoors",
center=dict(
lat=-7.78,
lon=110.365
),
zoom=10),
showlegend = False
)
fig.show()

Plot.ly draw reference lines on subplot?

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?

Hi-Low lines in Plotly Line Chart

I am trying to replicate this excel line chart in python using plotly.
Is there any way to add the high-low lines between the two line graphs in Plotly?
Thanks
Just an update on this post. Plotly doesn't seem to have a property to draw lines between points of 2 line plots. So I made the connecting lines as an array of trace and then plotted them on the same figure. Here's a snapshot of resulting plot
:
trace_1 = go.Scatter(x=x_arr, y=y1_arr, name='plot1', line=dict(color = ('royalblue')), mode='lines+markers')
trace_2 = go.Scatter(x=x_arr, y=y2_arr, name='plot2', line=dict(color = ('orange')), mode='lines+markers')
layout_1 = go.Layout(
height=420,
width=800,
title=go.layout.Title(
text='title',
),
xaxis=go.layout.XAxis(
title='x axis',
),
yaxis=go.layout.YAxis(
title='y axis',
)
)
data = []
trace_3_arr = np.array([])
for i in range(0, len(x_arr)):
trace_i = go.Scatter(x=[x_arr[i], x_arr[i]], y=[y1_arr[i], y2_arr[i]], line=dict(color = ('black'), width=1), showlegend=False)
trace_3_arr = np.append(trace_3_arr, trace_i)
data.append(trace_i)
data.append(trace_1)
data.append(trace_2)
fig = go.Figure(data=data, layout=layout_1)
plot(fig)

Categories