bmikolaj
bmikolaj

Reputation: 486

How do you add labels to a plotly boxplot in python?

I have the following code;

y = errnums
err_box = Box(
    y=y,
    name='Error Percent',
    boxmean='sd',
    marker=Marker(color='red'),
    boxpoints='all',
    jitter=0.5,
    pointpos=-2.0
)
layout = Layout(
    title='Error BoxPlot',
    height=500,
    width=500
)
fig = Figure(data=Data([err_box]), layout=layout)
plotly.image.save_as(fig, os.path.join(output_images, 'err_box.png'))

Which generates the following image; img

What I would like to do is the following two things;

1) Add % next to the y-axis numbers. (Instead of having a traditional y-axis label saying "Error (%)")

2) Label all the vital points: mean, first quartile, third quartile, and stdev. Ideally the label would be a 4 sig-fig ('.2f') number next to the line.

Also, the stdev is the dotted line, and the diamond represents 1 sigma? 2 sigma?

Upvotes: 2

Views: 10880

Answers (1)

Chris P
Chris P

Reputation: 2933

For labels, try annotations. You'll have to compute the quartiles and mean yourself to position the labels.

Simple example:

import plotly.plotly as py
from plotly.graph_objs import *

data = Data([
    Box(
        y=[0, 1, 1, 2, 3, 5, 8, 13, 21],
        boxpoints='all',
        jitter=0.3,
        pointpos=-1.8
    )
])
layout = Layout(
    annotations=Annotations([
        Annotation(
            x=0.3,
            y=8.822,
            text='3rd Quartile',
            showarrow=False,
            font=Font(
                size=16
            )
        )
    ])
)
fig = Figure(data=data, layout=layout)
plot_url = py.plot(fig)

Simple Python boxplot Simple boxplot with Plotly and Python

I recommend adding and positioning the annotations in the Plotly workspace, and then viewing the generated code:

Adding and editing annotations in the plotly workspace

Plotly boxplot with an annotation at the 3rd quartile

Python code to generate an annotation in Plotly

The diamond shows the mean, and +- 1 standard deviation away from it.

It's not currently possible to add a % to the y-axis labels.

Upvotes: 4

Related Questions