Matplotlib - How do I set ylim() for a series of plots?

后端 未结 3 1107
温柔的废话
温柔的废话 2021-01-13 09:07

I have a series of box plots I am trying to make, each of which has a different range. I tried setting ylim by determining the max and min of each separate series. Howe

3条回答
  •  时光取名叫无心
    2021-01-13 09:49

    As an alternative to what @unutbu suggested, you could avoid plotting the outliers and then use ax.margins(y=0) (or some small eps) to scale the limits to the range of the whiskers.

    For example:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame(np.random.poisson(5, size=(100, 5)))
    
    fig, ax = plt.subplots()
    #Note showfliers=False is more readable, but requires a recent version iirc
    box = df.boxplot(ax=ax, sym='') 
    ax.margins(y=0)
    plt.show()
    

    And if you'd like a bit of room around the largest "whiskers", use ax.margins(0.05) to add 5% of the range instead of 0% of the range:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame(np.random.poisson(5, size=(100, 5)))
    
    fig, ax = plt.subplots()
    box = df.boxplot(ax=ax, sym='')
    ax.margins(y=0.05)
    plt.show()
    

提交回复
热议问题