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

后端 未结 3 1119
温柔的废话
温柔的废话 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:41

    You could inspect the whiskers (maplotlib.lines.Line2D objects) returned by df.boxplot(). For example, if you call

    bp = df.boxplot(ax=ax)
    

    then bp['whiskers'] will be a list of Line2D objects. You can find the y-values for each line using

    yval = np.concatenate([line.get_ydata() for line in bp['whiskers']])
    

    and then use yval.min() and yval.max() to determine the desired y-limits.


    For example,

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    df = pd.DataFrame(np.random.poisson(5, size=(100, 5)))
    bp = df.boxplot(ax=ax)
    yval = np.concatenate([line.get_ydata() for line in bp['whiskers']])
    eps = 1.0
    ymin, ymax = yval.min()-eps, yval.max()+eps
    ax.set_ylim([ymin,ymax])
    plt.show()
    

    yields

提交回复
热议问题