Search code examples
pythonmatplotlibhistogram

Vertical and Horizontal figures on one plot


I would like to create sth like the following graph in matplotlib:

enter image description here

I have x = [0, 1, ..., 10], and for each x I have values from range [0, 60]. Lets say that the black line is the quantile of values for a given i from range x. For selected i I want to add horizontally histogram (with parameter density = True) like in the picture with the possibility to control the width of this histogram (in the picture it goes from 2 to 5 but I would like to set fixed width). How can I do that?


Solution

  • Yes, this is relatively straightforward with inset_axes:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    x = np.random.randn(100)
    ax.plot(x)
    ylim = ax.get_ylim()
    
    histax = ax.inset_axes([0.3, 0, 0.2, 1], transform=ax.transAxes)
    histax.hist(x, orientation='horizontal', alpha=0.5 )
    histax.set_facecolor('none')
    histax.set_ylim(ylim)
    
    plt.show()
    

    enter image description here

    You will probably want to clean up the axes etc, but that is the general idea.