Adding a scatter of points to a boxplot using matplotlib

后端 未结 3 1418
一向
一向 2020-12-07 23:16

I have seen this wonderful boxplot in this article (Fig.2).

\"A

As you can see, thi

3条回答
  •  余生分开走
    2020-12-08 00:05

    What you're looking for is a way to add jitter to the x-axis.

    Something like this taken from here:

    bp = titanic.boxplot(column='age', by='pclass', grid=False)
    for i in [1,2,3]:
        y = titanic.age[titanic.pclass==i].dropna()
        # Add some random "jitter" to the x-axis
        x = np.random.normal(i, 0.04, size=len(y))
        plot(x, y, 'r.', alpha=0.2)
    

    enter image description here

    Quoting the link:

    One way to add additional information to a boxplot is to overlay the actual data; this is generally most suitable with small- or moderate-sized data series. When data are dense, a couple of tricks used above help the visualization:

    1. reducing the alpha level to make the points partially transparent
    2. adding random "jitter" along the x-axis to avoid overstriking

    The code looks like this:

    import pylab as P
    import numpy as np
    
    # Define data
    # Define numBoxes
    
    P.figure()
    
    bp = P.boxplot(data)
    
    for i in range(numBoxes):
        y = data[i]
        x = np.random.normal(1+i, 0.04, size=len(y))
        P.plot(x, y, 'r.', alpha=0.2)
    
    P.show()
    

提交回复
热议问题