Python Matplotlib Boxplot Color
Asked Answered
M

4

52

I am trying to make two sets of box plots using Matplotlib. I want each set of box plot filled (and points and whiskers) in a different color. So basically there will be two colors on the plot

My code is below, would be great if you can help make these plots in color. d0 and d1 are each list of lists of data. I want the set of box plots made with data in d0 in one color, and the set of box plots with data in d1 in another color.

plt.boxplot(d0, widths = 0.1)
plt.boxplot(d1, widths = 0.1)
Mensa answered 2/2, 2017 at 8:34 Comment(1)
Matplotlib has really helpful documentation just for this.Opponent
P
67

To colorize the boxplot, you need to first use the patch_artist=True keyword to tell it that the boxes are patches and not just paths. Then you have two main options here:

  1. set the color via ...props keyword argument, e.g.
    boxprops=dict(facecolor="red"). For all keyword arguments, refer to the documentation
  2. Use the plt.setp(item, properties) functionality to set the properties of the boxes, whiskers, fliers, medians, caps.
  3. obtain the individual items of the boxes from the returned dictionary and use item.set_<property>(...) on them individually. This option is detailed in an answer to the following question: python matplotlib filled boxplots, where it allows to change the color of the individual boxes separately.

The complete example, showing options 1 and 2:

import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(0.1, size=(100,6))
data[76:79,:] = np.ones((3,6))+0.2

plt.figure(figsize=(4,3))
# option 1, specify props dictionaries
c = "red"
plt.boxplot(data[:,:3], positions=[1,2,3], notch=True, patch_artist=True,
            boxprops=dict(facecolor=c, color=c),
            capprops=dict(color=c),
            whiskerprops=dict(color=c),
            flierprops=dict(color=c, markeredgecolor=c),
            medianprops=dict(color=c),
            )


# option 2, set all colors individually
c2 = "purple"
box1 = plt.boxplot(data[:,::-2]+1, positions=[1.5,2.5,3.5], notch=True, patch_artist=True)
for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
        plt.setp(box1[item], color=c2)
plt.setp(box1["boxes"], facecolor=c2)
plt.setp(box1["fliers"], markeredgecolor=c2)
            

plt.xlim(0.5,4)
plt.xticks([1,2,3], [1,2,3])
plt.show()

enter image description here

Photoelectrotype answered 2/2, 2017 at 9:0 Comment(3)
Thanks for the excellent answer. Minor nitpick: "Then you have two main options here" ... and then you list 3 :-) . Which reminds me of the joke "The 4 apostles are the following three: Peter and Paul" (sorry couldn't resist)Labaw
Highlight it again: it is vital to add patch_artist=True otherwise the boxes will be Line2Ds instead of Patchs, in which case you can not set face colors to them since those are just lines.Malayopolynesian
googled the joke, got a painting. [x y z w] --> [x y z] --> [x y]Obola
S
49

You can change the color of a box plot using setp on the returned value from boxplot(). This example defines a box_plot() function that allows the edge and fill colors to be specified:

import matplotlib.pyplot as plt

def box_plot(data, edge_color, fill_color):
    bp = ax.boxplot(data, patch_artist=True)
    
    for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
        plt.setp(bp[element], color=edge_color)

    for patch in bp['boxes']:
        patch.set(facecolor=fill_color)       
        
    return bp
    
example_data1 = [[1,2,0.8], [0.5,2,2], [3,2,1]]
example_data2 = [[5,3, 4], [6,4,3,8], [6,4,9]]

fig, ax = plt.subplots()
bp1 = box_plot(example_data1, 'red', 'tan')
bp2 = box_plot(example_data2, 'blue', 'cyan')
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ['Data 1', 'Data 2'])
ax.set_ylim(0, 10)
plt.show()

This would display as follows:

box plot screenshot

Skillless answered 2/2, 2017 at 8:56 Comment(3)
You missed the markeredgecolor of the fliers. ;-)Photoelectrotype
How would you add a label for the blue and a label for the brown boxplots?Cellule
The bp returned from the function can be used to make a call to ax.legend(), I've updated the example to show you howSkillless
C
13

This question seems to be similar to that one (Face pattern for boxes in boxplots) I hope this code solves your problem

import matplotlib.pyplot as plt

# fake data
d0 = [[4.5, 5, 6, 4],[4.5, 5, 6, 4]]
d1 = [[1, 2, 3, 3.3],[1, 2, 3, 3.3]]

# basic plot
bp0 = plt.boxplot(d0, patch_artist=True)
bp1 = plt.boxplot(d1, patch_artist=True)

for box in bp0['boxes']:
    # change outline color
    box.set(color='red', linewidth=2)
    # change fill color
    box.set(facecolor = 'green' )
    # change hatch
    box.set(hatch = '/')

for box in bp1['boxes']:
    box.set(color='blue', linewidth=5)
    box.set(facecolor = 'red' )

plt.show()

enter image description here

Contemptuous answered 2/2, 2017 at 9:7 Comment(2)
How do you change the fill of individual boxplot? For example, how can I set two different fill colours for bp0 and bp1?Opponent
Nevermind, I solved my problem using the documentation tutorial.Opponent
D
5

Change the color of a boxplot

import numpy as np 
import matplotlib.pyplot as plt

#generate some random data
data = np.random.randn(200)
d= [data, data]
#plot
box = plt.boxplot(d, showfliers=False)
# change the color of its elements
for _, line_list in box.items():
    for line in line_list:
        line.set_color('r')

plt.show()

enter image description here

Debose answered 10/4, 2019 at 20:1 Comment(1)
Weirdly only this solution worked for me. I assume this will be needed for older matplotlib versions. (Version 1.3.1 worked with this).Levity

© 2022 - 2024 — McMap. All rights reserved.