user3329732
user3329732

Reputation: 343

Why don't colors change in matplotlib boxplot?

I make a boxplot with matplotlib:

import pandas as pd
import matplotlib.pyplot as plt

A = pd.DataFrame([54.183933149245775,98.14228839908178,97.56790596547185,81.28351460722497,116.36733517668105,93.64706288367272,107.68860349692736,109.65565349602194,88.58717530217115,54.87561132504807,137.89097514410435,116.90021701471281,121.41252555476005,102.68420408219474,107.32642696333856,
 120.27307064490907,114.3674635060443,91.38936314166017,149.0476109186976,121.76625219213736,155.6027360469248,115.86331915425764,99.35036421024546,104.93804853361358,115.64286896238708,129.51583078514085,116.30239399660411,97.58582728510798,119.59975852978403,103.68594428632996], columns=['A'])

fig, ax = plt.subplots(1,1)
A.boxplot(grid=False, fontsize=12, notch=True,
            flierprops = dict(markersize=10, markeredgecolor ='red', markerfacecolor='b'),
            boxprops = dict(linewidth=2, color='red'))
fig.show()

enter image description here

The flier props will change the colors and marker size. However, for "boxprops", the linewidth can change but the color NEVER changes (here it stays blue). Does anybody know why? Also, where is the matplotlib documentation giving all the options for these properties?

Upvotes: 0

Views: 472

Answers (1)

Anwarvic
Anwarvic

Reputation: 12992

You can do that by doing two things actually,

  • First, determine the return_type of your boxplot
  • Second, change the color of the boxes key like so:

Here, I will change the boxes into green

import pandas as pd
import matplotlib.pyplot as plt

A = pd.DataFrame([54.183933149245775,98.14228839908178,97.56790596547185,81.28351460722497,116.36733517668105,93.64706288367272,107.68860349692736,109.65565349602194,88.58717530217115,54.87561132504807,137.89097514410435,116.90021701471281,121.41252555476005,102.68420408219474,107.32642696333856,
 120.27307064490907,114.3674635060443,91.38936314166017,149.0476109186976,121.76625219213736,155.6027360469248,115.86331915425764,99.35036421024546,104.93804853361358,115.64286896238708,129.51583078514085,116.30239399660411,97.58582728510798,119.59975852978403,103.68594428632996], columns=['A'])

fig, ax = plt.subplots(1,1)
bp = A.boxplot(grid=False, fontsize=12, notch=True,
               flierprops = dict(markersize=10, markeredgecolor ='red', markerfacecolor='b'),
                boxprops = dict(linewidth=2, color='red'),
                return_type='dict')  # add this argument

# set the color of the boxes to green
for item in bp['boxes']:
    item.set_color('g')
plt.show()

And this will show the following graph: enter image description here

Upvotes: 2

Related Questions