6

I am trying to create boxplot from pandas dataframe using matplotlib.

I am able to get the boxplot and change the linewidth of outlines and median lines, but I would like to change all the colors to black. I tried several ways as described in Pandas boxplot: set color and properties for box, median, mean and Change the facecolor of boxplot in pandas.

However, none of them worked for my case.

Could someone solve these problems?

Here are my codes:

version: python 3.6.5

    import pandas as pd
    from pandas import DataFrame, Series
    import matplotlib.pyplot as plt

    df = pd.read_excel("training.xls")

    fig = plt.figure()
    ax = fig.add_subplot(111)

    boxprops = dict(color="black",linewidth=1.5)
    medianprops = dict(color="black",linewidth=1.5)


    df.boxplot(column=["MEAN"],by="SrcID_Feat",ax=ax,
              boxprops=boxprops,medianprops=medianprops)

    plt.grid(False)

Result

Screen Shot

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
moomin
  • 61
  • 1
  • 1
  • 2

2 Answers2

5

Here is a way to solve your problem (details which are not relevant for the question are omitted):

fig, ax = plt.subplots()
box_plot = ax.boxplot(..., patch_artist=True)
for median in box_plot['medians']:
    median.set_color('black')

median is an object of type matplotlib.lines.Line2D which exposes a method set_color which can be used to set the color of each box.

PolarBear
  • 145
  • 3
  • 8
4

I found that unless I add the argument patch_artist=True, none of the boxprops dictionaries have any effect on the boxplot. For example, when I generated a boxplot where I changed the facecolor to yellow, I had to use the following coding:

plt.boxplot(boxplot_data, positions=[1], patch_artist=True, boxprops=dict(facecolor='yellow'), showmeans=True)
BenT
  • 3,172
  • 3
  • 18
  • 38