Search code examples
pythonplotly

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.


Solution

  • 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