9951 explained code solutions for 126 technologies


python-matplotlibHow to add legend to boxplot


import matplotlib.pyplot as plt

bp = plt.boxplot([[2,3,6,2,4,5,1,2], [4,5,7,17,3]], notch=True, patch_artist=True)

bp['boxes'][0].set_facecolor('red')
bp['boxes'][0].set_color('red')
bp['boxes'][1].set_facecolor('green')
bp['boxes'][1].set_color('green')

plt.legend([bp["boxes"][0], bp["boxes"][1]], ['A', 'B'], loc='upper right')

plt.show()ctrl + c
import matplotlib.pyplot as plt

loads Matplotlib module to use plotting capabilities

.boxplot(

plots boxplot (features of a given set of values: minimum, first quartile, median, third quartile and maximum)

set_facecolor

sets box background

set_color

set boxplot line color

.legend(

show and configure legend

.show()

render chart in a separate window


How to add legend to boxplot, python matplotlib

Usage example

import matplotlib.pyplot as plt

bp = plt.boxplot([[2,3,6,2,4,5,1,2], [4,5,7,17,3]], notch=True, patch_artist=True)

bp['boxes'][0].set_facecolor('red')
bp['boxes'][0].set_color('red')
bp['boxes'][1].set_facecolor('green')
bp['boxes'][1].set_color('green')

plt.legend([bp["boxes"][0], bp["boxes"][1]], ['A', 'B'], loc='upper right')

plt.show()