python - สรุปขีด จำกัด แกน y สำหรับเส้นค่าเฉลี่ยในแปลงความหนาแน่น

Aug 18 2020

ฉันมี dataframe ง่ายๆนี้:

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

อย่างไรก็ตามฉันมีปัญหาในการพยายามสรุปymaxอาร์กิวเมนต์plt.vlines()เนื่องจากฉันต้องการรับค่าแกน y สูงสุดของแต่ละพล็อตความหนาแน่นเพื่อที่จะพล็อต vline เฉลี่ยของแต่ละพล็อตตามนั้น ฉันได้ลองใช้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()

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