Matplotlib-如何为一系列绘图设置ylim()?

2024-05-14 21:14:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的方块图,每个都有不同的范围。我试着通过确定每个独立序列的最大值和最小值来设置ylim。但是,在许多情况下,最小值是一个异常值,因此图被压缩。我怎样才能选择相同的限制所使用的'胡须'的情节(加上一个小幅度)?

我现在正在做:

[In]
ax = df['feature'].boxplot()
ymax = max(df['feature']
ymin = min(df['feature']
ax.set_ylim([ymax,ymin])

我想让ymax,ymin成为这个盒子里的胡须。


Tags: indf情况序列axminmaxfeature
3条回答

作为@unutbu建议的替代方法,您可以避免绘制异常值,然后使用ax.margins(y=0)(或一些小的eps)将限制范围扩展到晶须的范围。

例如:

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()

enter image description here

如果你想在最大的“胡须”周围留点空间,可以使用ax.margins(0.05)来添加5%的范围而不是0%的范围:

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()

enter image description here

您可以检查由df.boxplot()返回的晶须(maplotlib.lines.Line2D对象)。例如,如果你打电话给

bp = df.boxplot(ax=ax)

然后bp['whiskers']将是Line2D对象的列表。您可以使用

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

然后使用yval.min()yval.max()来确定所需的y-limits


例如

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()

收益率 enter image description here

可以在boxplot中设置showfliers=False,这样就不会绘制异常值。

由于您特别询问了胡须,this is how they are calculated,默认值为1.5:

whis : float, sequence (default = 1.5) or string

As a float, determines the reach of the whiskers past the first and third quartiles (e.g., Q3 + whis*IQR, IQR = interquartile range, Q3-Q1). Beyond the whiskers, data are considered outliers and are plotted as individual points. Set this to an unreasonably high value to force the whiskers to show the min and max values. Alternatively, set this to an ascending sequence of percentile (e.g., [5, 95]) to set the whiskers at specific percentiles of the data. Finally, whis can be the string ‘range’ to force the whiskers to the min and max of the data. In the edge case that the 25th and 75th percentiles are equivalent, whis will be automatically set to ‘range’.

您可以执行相同的计算,并将ylim设置为该值。

相关问题 更多 >

    热门问题