Search code examples
pythonpandasmatplotlibtransparency

Set boxplot 'boxes' facecolor transparency


I'm looking for a way to set transparency for the boxplot facecolor. Now it appears 'red' with alpha=1. How do I change it to 'red' with alpha of 0.5 for example while keeping the boxes edge-color non-transparent 'black'? I only want transparency for the facecolor, not for the edgecolor. Any ideas?

Tried code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as cls
import matplotlib

matplotlib.interactive(True)

df = pd.DataFrame({"A": [18,28,29,32,35,36,37,37,39,40,42,42,46,48,54,56,57,61,61,62,63,65],
                   "B":  [9,13,17,15,23,21,24,28,26,30,29,30,38,42,40,48,40,51,54,50,51,57],
                   "C": [1,98,65,47,58,95,24,5,63,7,41,5,6,84,56,96,33,25,61,94,68,83]})

columns = ['A', 'B']
df_data = df.loc[:, columns]

def boxplot(y_lims, y_lime):
    plt.figure(figsize=((12.0 / 2.54), (7.42 / 2.54)), facecolor=None, edgecolor='black')  
    fig, ax = plt.subplots() 
    boxprops = dict(linestyle='-', linewidth=0.6)  
    bp = df_data.boxplot(ax=ax, grid=False, showfliers=False, boxprops=boxprops, showmeans=True, return_type='dict', patch_artist=True)
    [patch.set(facecolor='red', alpha=1.0) for patch in bp['boxes']]   #if alpha=0.5; both face and edge color are transparent, I only want the facecolor to be transparent 
    [patch.set_edgecolor('black') for patch in bp['boxes']]
    [item.set_color('black') for item in bp['whiskers']]
    [item.set_color('black') for item in bp['caps']]
    [item.set_marker('.') for item in bp['means']]
    [item.set_markerfacecolor('black') for item in bp['means']]
    [item.set_markeredgecolor('black') for item in bp['means']]
    [item.set_color('black') for item in bp['medians']]

    ax.set_ylim(y_lims, y_lime)    
    plt.show()


if __name__ == '__main__':

    Boxplot_a = boxplot(None, None)

Note: - rgba-colors didn't do the trick, the alpha is not recognised for some reason


Solution

  • Once alpha is set for the whole path patch, possible alpha values in RGBA edge and face colors are ignored. Pandas sets alpha to 1 internally.

    So in order to make it work you need to re-set alpha to None and then specify the alpha channel in the colors as needed (e.g. 0.5 for face and 1 for edge colors):

    [patch.set(alpha=None, facecolor=(1,0,0,.5)) for patch in bp['boxes']]
    

    enter image description here

    Edit: this is already fixed and will be available in version 1.1.0 (third item here). Then you can simply do

    boxprops = dict(linestyle='-', linewidth=0.6, facecolor=(1,0,0,.5), edgecolor='k')
    

    (no need to change the patches afterwards)