简体   繁体   中英

How to add a dot/point in a plotly scatterplot

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.

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

在此处输入图像描述

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: 阴谋

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 n.netheless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM