python-밀도 플롯의 평균선에 대한 y 축 제한 일반화
Aug 18 2020
이 간단한 데이터 프레임이 있습니다.
df = pd.DataFrame({"X": np.random.randint(50,53,size=100),
"Y": np.random.randint(200,300,size=100),
"Z": np.random.randint(400,800,size=100)})
그리고 많은 열 (모두 숫자)이 있으므로 특정 플롯을 수행하기 위해이 루프를 수행했습니다.
for i in df.columns:
data = df[i]
data.plot(kind="kde")
plt.vlines(x=data.mean(),ymin=0, ymax=0.01, linestyles="dotted")
plt.show()
그러나 각 플롯의 평균 vline을 그에 따라 플롯하기 위해 각 밀도 플롯의 최대 y 축 값 을 가져와야하므로의 ymax
인수 를 일반화하는 데 어려움이 plt.vlines()
있습니다. 로 시도했지만 np.argmax()
작동하지 않는 것 같습니다.
어떤 제안?
답변
3 Ynjxsjmh Aug 18 2020 at 16:05
pandas.DataFrame.plot()matplotlib.axes.Axes객체를 반환 합니다. get_ylim()함수를 사용 하여 ymin 및 ymax를 얻을 수 있습니다 .
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"X": np.random.randint(50,53,size=100),
"Y": np.random.randint(200,300,size=100),
"Z": np.random.randint(400,800,size=100)})
for i in df.columns:
data = df[i]
ax = data.plot(kind="kde")
ymin, ymax = ax.get_ylim()
plt.vlines(x=data.mean(),ymin=ymin, ymax=ymax, linestyles="dotted")
plt.show()
2 JohanC Aug 18 2020 at 16:20
평균에 해당하는 kde 값을 얻으려면 플롯에서 곡선을 추출하여 평균 위치에서 보간 할 수 있습니다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({"X": 20 + np.random.randint(-1, 2, size=100).cumsum(),
"Y": 30 + np.random.randint(-1, 2, size=100).cumsum(),
"Z": 40 + np.random.randint(-1, 2, size=100).cumsum()})
fig, ax = plt.subplots()
for col in df.columns:
data = df[col]
data.plot(kind="kde", ax=ax)
x = data.mean()
kdeline = ax.lines[-1]
ymax = np.interp(x, kdeline.get_xdata(), kdeline.get_ydata())
ax.vlines(x=data.mean(), ymin=0, ymax=ymax, linestyles="dotted")
ax.set_ylim(ymin=0) # ax.vlines() moves the bottom ylim; set it back to 0
plt.show()
![](https://post.nghiatu.com/assets/images/s/DsbV3.png)
1 ALollz Aug 18 2020 at 16:01
사용 plt.axvline. 한계는 [0,1] 범위의 숫자로 지정합니다. 0은 플롯의 맨 아래, 1은 맨 위입니다.
for i in df.columns:
data = df[i]
data.plot(kind="kde")
plt.axvline(data.mean(), 0, 1, linestyle='dotted', color='black')
plt.show()
![](https://post.nghiatu.com/assets/images/s/5iCj8.png)