Search code examples
pythonplotly

How to add labels to plotly Box chart like Scatter chart?


I couldn't find the way to add text labels to plotly/dash box plot like you could add it to a scatterplot. In the example below, for ScatterPlot x=qty, y=price and you can then add Salesperson to the graph when the cursor is on Marker. For adding this I use the 'text' argument.

In the second example for BoxPlot when x=date, y=price I want to add salesperson in the same way. It would be very useful in case of outliers to see immediately who was the salesperson for that purchase. I looked in the documentation, but there is no clue. I assume it's not possible but still decided to try my luck here.

scatterplot:

import plotly.offline as pyo
import plotly.graph_objs as go


purchase={'date':['11/03/2021','12/03/2021','14/03/2021','11/03/2021'],
          'price':[300, 400,200, 200],
          'currency':['eur', 'usd','usd','usd'],
          'qty':[200, 300, 400, 500],
          'salesman':['AC', 'BC', "CC", 'DC']}
pur=pd.DataFrame(purchase)
pur



data = [go.Scatter(
    x = pur['qty'],
    y = pur['price'],
    mode = 'markers',
    text=pur['salesman'],
    marker = dict(
        size = 12,
        color = 'rgb(51,204,153)',
        symbol = 'pentagon',
        line = dict(
            width = 2,
        )
    )
)]
layout = go.Layout(
    title = 'Random Data Scatterplot', 
    xaxis = dict(title = 'Some random x-values'), 
    yaxis = dict(title = 'Some random y-values'), 
    hovermode ='closest' 
)
fig = go.Figure(data=data, layout=layout)

fig.show()

boxplot:

import plotly.offline as pyo
import plotly.graph_objs as go

x = pur['date']
y = pur['price']

data = [
    go.Box(
        y=y,
        x=x,
        text=pur['salesman']
    )
]
layout = go.Layout(
    title = 'box_plot'
)
fig = go.Figure(data=data, layout=layout)
fig.show()

Solution

  • The data you currently have is not suitable for boxplot. If you try to plot a boxplot with your data, the list [300, 400,200, 200] is used only once for the first date. For the other dates, there is no data.

    I will show a simpler example with my own data.

    dataset.csv

    salesman,sales
    alan,1.8
    bary,2.3
    copa,4.2
    dac,1.19
    eila,2.3
    foo,2.5
    gary,0.1
    holland,10
    

    code

    import plotly.graph_objs as go
    import pandas as pd
    import plotly.io as pio
    pio.renderers.default = 'browser'
    
    df = pd.read_csv("deletelater")
    
    fig = go.Figure()
    fig.add_trace(go.Box(
        y=df["sales"],
        name='12/12/22',
        customdata=df["salesman"],
        hovertemplate='<b>sales: %{y}</b><br>salesperson: %{customdata}'
    ))
    
    
    fig.show()
    

    Diagram

    enter image description here

    As you can see, the name of the outlier salesperson is displayed on the hover label.