1

I have plotted a set of data in a boxplot, and I have added a line in the plot. I want to have the labels of the median and mean in the legend, and I have got it. However, I'm also trying to add the label of the line. I have tried to add the label of the line in similar ways as for the boxplot and looked at other examples but none does match my code. I do not get it to work..

This is the code:

import matplotlib.pyplot as plt
import numpy as np


def box_plot():
    
    data = np.array([
        [17.7, 22.9, 17.6],     #M4 Ratio 17
        [17.3, 22.0, 16.4],     #M5 Ratio 13
        [15.8, 21.4, 16.0],     #M6 Ratio 10
        [16.1, 21.8, 17.6]    #M7 Ratio 8.8
    ])
    
    labels = ['AS', 'JB', 'EG']
    
    
    meanlineprops = dict(linestyle='solid', linewidth=1.5, color='black')
    medianprops = dict(linestyle='dashed', linewidth=1.5, color='black')
    
    

    fig = plt.figure(figsize=(5,5), layout='constrained')
    axes = fig.subplots(ncols=1, nrows=1 )
    bp = axes.boxplot(data, labels=labels, showmeans=True, meanline=True, meanprops=meanlineprops, medianprops=medianprops)
    axes.set_title('A2')
    axes.grid()
    
    
    volume_A2 = 18.77
    line = axes.plot([0,4], [volume_A2, volume_A2], "k--", linewidth=1, color='black', label='True volume')
    axes.set_xlim(0.5, 3.5)
    
    axes.set_ylabel('Volume (ml)')
    axes.set_xlabel('Medical Physicist')
    
   
    axes.legend([ bp['means'][0], bp['medians'][0], line], [ 'Mean', 'Median'])
    

Thankful for the help!

1 Answer 1

0

Firstly I have changed that code part to that. Because this line gave error.

line = axes.plot([0,4], [volume_A2, volume_A2], "--", linewidth=1, color='k', label='True volume')

You will face that error if you use line as list in your lenged.

UserWarning: Legend does not support handles for list instances.
A proxy artist may be used instead.

For fix that problem u can use line[0] in your legend u should change your legend to that.

axes.legend([ bp['means'][0], bp['medians'][0], line[0]], [ 'Mean', 'Median', 'True Volume'])

I hope this solution can help you.

Not the answer you're looking for? Browse other questions tagged or ask your own question.