pythonmatplotlibboxplotoverlap

How to avoid overlapping between boxes and whiskers in boxplot?


When trying not to show outlines while plotting boxes in a boxplot, whiskers may overlap. Is there a way to avoid it? (perhaps changing the order patches are display and send whiskers behind)

Consider this minimal reproducible example:

import matplotlib.pyplot as plt

bp = plt.boxplot([1,2,3], patch_artist=True)
plt.setp(bp['boxes'], color='#5454c6')
for item in ['whiskers', 'caps']:
    plt.setp(bp[item], lw=5)
plt.show()

enter image description here


Solution

  • The main problem is the linewidth extending the line length. See https://stackoverflow.com/a/66330477/13636407

    So main solution would be to use setp(..., solid_capstyle="butt"). But also drawing the whiskers below the boxes as mentioned in comments will do the job.

    Note that you probably don't want to use solid_capstyle="butt" for the caps, so the zorder way would be the easiest if it doesn't conflict (e.g. transparent box)

    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(16, 4))
    
    bp = ax1.boxplot([1, 2, 3], patch_artist=True)
    plt.setp(bp["boxes"], color="#5454c6")
    for item in ["whiskers", "caps"]:
        plt.setp(bp[item], lw=10)
    
    bp = ax2.boxplot([1, 2, 3], patch_artist=True)
    plt.setp(bp["boxes"], color="#5454c6")
    for item in ["whiskers", "caps"]:
        plt.setp(bp[item], lw=10, solid_capstyle="butt")
    
    bp = ax3.boxplot([1, 2, 3], patch_artist=True)
    plt.setp(bp["boxes"], color="#5454c6")
    for item in ["whiskers", "caps"]:
        plt.setp(bp[item], lw=10, solid_capstyle="butt", zorder=0)
    
    plt.show()
    

    boxplots