Search code examples
python-3.xmatplotlibdate-rangescatter

Matplotlib - Plot 1D range line and scatter points on it


Any suggest to reproduce this kind of graph ?

enter image description here

I am trying to reproduce only whiskers of a generic boxplot. Vertical lines rapresent a specific range and i would plot points on them in order to highlight which points are inside or outside. My difficulty is to draw extrema borders of these 1D range lines. Thank you


Solution

  • This is called a boxplot (matplotlib). If you just want a line, you can change one the options in the arguments (widths). Set it to 0, if you just want a line. One problem is that the caps also change their width to zero. You can fix this by settings the caps xdata argument to some value (e.g. -0.1 to 0.1).

    You can add data points using plt.scatter().

    I hope this helped you.

    Code example here:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    # set some random data
    data = np.array([20,16,14,1,2,3,4,4.5,7.7,5,6,7,8,9,5,1.1])
    x = np.array([1]*len(data))
    df = pd.DataFrame(data)
    
    # create boxplot with 0 widths (just a line)
    bp = plt.boxplot(df, widths=0)
    
    # change caps width
    for cap in bp['caps']:
        cap.set(xdata=cap.get_xdata() + (-.1,.1))
    
    # get upper and lower cap value
    lb = bp['caps'][0].get_ydata()[0]
    ub = bp['caps'][1].get_ydata()[0]
    
    # add scatter plot
    plt.scatter(x[(data < lb) | (data > ub)], data[(data < lb) | (data > ub)], color='red')
    plt.scatter(x[(data>=lb) & (data<= ub)], data[(data>=lb) & (data<= ub)], color='green')
    plt.show()
    

    Result:

    boxplot