3

I already have a scatterplot (interactive) made with plotly, and I would like to add one dot, not necessarily interactive, in a specific coordinate (to mark the median). How can I add it?

fig = px.scatter(df_b, x="EAD", y="RAR", size="Margen_bruto", hover_name="Cliente", hover_data={'EAD': ':.0f', 'RAR': ':.0%', 'Margen_bruto': ':.0f'}, size_max=30, trendline='lowess', trendline_color_override='black', trendline_scope='overall', title="BÉLGICA dic 2019 - 46 clientes") 

I've already used functions like fig.add_annotation and fig.add_hline to add text and lines to my graph, but I can't seem to be able to add just one point.

2 Answers 2

9

There are several ways to add it, but it can be added with add_scatter(); the data required for xy must be a list or an array, so the xy value should be a list. Since you did not provide any data, I adapted your code from the example in the reference.

import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", trendline="lowess", trendline_color_override='black', trendline_scope='overall', ) fig.add_scatter(x=[df['total_bill'].median()], y=[df['tip'].median()], marker=dict( color='red', size=10 ), name='median') fig.show() 

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Great! I have a further question. The hover data over the median point marks two data (EAD and RAR). I would like to put the RAR as a percentage and the EAD as a number without decimals. How can I do that?
Since your data is unknown, I will comment with my response that the hover data displayed in the current response shows the median value of each. If you want to customize it further with a hover template, you can do so with the following code. fig.add_scatter(x=[df['total_bill'].median()], y=[df['tip'].median()], hovertemplate='total_bill_median: %{x}<br>tip: %{y}',...)
1

Piggybacking on r-begginners' answer.

From Plotly documentation:

Regardless of how a graph object figure was constructed, it can be updated by adding additional traces to it and modifying its properties.

import plotly.express as px import plotly.graph_objects as go df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", trendline="lowess", trendline_color_override='black') fig.add_trace(go.Scatter(x=[20], y=[10], marker_symbol='x', marker_size=15)) 

And the result: Plot

add_scatter is a convenience method provided by plotly:

As an alternative to the add_trace() method, graph object figures have a family of methods of the form add_{trace} (where {trace} is the name of a trace type) for constructing and adding traces of each trace type.

It is certainly a more readable option, but I felt it is helpful to know about how traces are handled nonetheless.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.