02 February 2021

Changing the colors in Pandas boxplot

 Normally, it's just one Google search that gets you to a good example for plotting any graph using Pandas or Matplotlib. Not so for boxplots. Every example I saw was ordinary and didn't show the advanced options for colouring the plot. So here's a quick demo:


import math
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
#Named colors: https://matplotlib.org/3.1.0/gallery/color/named_colors.html

data = {"A": [1,2,3,4,10,56,32], "B": [2,4,6,3,2.4,0,0], "C": [1,4,0,10,20,5,2], "D": [2,3,6,2,3,40,-1]}
for k in data.keys():#convert the zeroes to NaN, so that it does not mess up the boxplot
    data[k] = [x if x != 0 else math.nan for x in data[k]]
figWidth = 4; figHeight = 4.1;
boxproperties = dict(linestyle='-', linewidth=1.5)
medianproperties = dict(linestyle='-', linewidth=1.5)
flierproperties = dict(markerfacecolor = 'lightgrey', markeredgecolor = 'lightgrey')
colors = dict(boxes='dimgrey', whiskers='darkgray', medians='yellowgreen', caps='dimgrey')
df = pd.DataFrame(data, columns=list(sorted(data.keys())))
df.plot.box(grid=False, patch_artist=True, showmeans = False,
            sym='.', color = colors, boxprops=boxproperties,
            medianprops=medianproperties, flierprops = flierproperties,
            figsize=(figWidth, figHeight))
plt.title("values")
plt.ylabel("y label")
plt.xlabel("x label")               
plt.savefig('myPlot.eps', format='eps', dpi=1200)
plt.show()   



There are of course more styles that could be presented.

Say thank you or donate