pythonmatplotlibvisualizationhistogramboxplot

Matplotlib: Can we draw a histogram and a box plot on a same chart?


I have a question about drawing a histogram and a box plot Matplotlib.

I know I can draw a histogram and a box plot individually. My question is, is it possible to draw them on the same graph, such as a chart shown in this website? Springer Images

Thank you very much!


Solution

  • There are several ways to achieve this with matplotlib. The plt.subplots() method, and the AxesGrid1 and gridspec toolkits all provide very elegant solutions, but might take time to learn.

    A simple, brute-force way to do this would be to manually add the axes objects to a figure yourself.

    import numpy as np
    import matplotlib.pyplot as plt
    
    # fake data
    x = np.random.lognormal(mean=2.25, sigma=0.75, size=37)
    
    # setup the figure and axes
    fig = plt.figure(figsize=(6,4))
    bpAx = fig.add_axes([0.2, 0.7, 0.7, 0.2])   # left, bottom, width, height:
                                                # (adjust as necessary)
    histAx = fig.add_axes([0.2, 0.2, 0.7, 0.5]) # left specs should match and
                                                # bottom + height on this line should
                                                # equal bottom on bpAx line
    # plot stuff
    bp = bpAx.boxplot(x, notch=True, vert=False)
    h = histAx.hist(x, bins=7)
    
    # confirm that the axes line up 
    xlims = np.array([bpAx.get_xlim(), histAx.get_xlim()])
    for ax in [bpAx, histAx]:
        ax.set_xlim([xlims.min(), xlims.max()])
    
    bpAx.set_xticklabels([])  # clear out overlapping xlabels
    bpAx.set_yticks([])  # don't need that 1 tick mark
    plt.show()