วิธีการเพิ่ม Error Bar ใน Matplotlib line plot?
Oct 10 2020
ฉันมีชุดข้อมูลต่อไปนี้ซึ่งใช้ในการลงจุดเส้น พล็อตจะได้รับเป็นmeanของค่าที่ได้รับจากข้อมูล ฉันต้องการเพิ่มแถบข้อผิดพลาดในพล็อตนี้ซึ่งจะแสดงค่าเบี่ยงเบนมาตรฐาน ฉันได้ค้นหาคำตอบที่แตกต่างกัน แต่ในส่วนใหญ่พวกเขาได้กำหนดไว้อย่างชัดเจนxและyชัดเจน แต่ที่นี่ฉันคำนวณพล็อตโดยตรงจากดาต้าเฟรม จะเพิ่มแถบข้อผิดพลาดลงในพล็อตนี้ได้อย่างไร?
Dataframe df
UserId | date |-7|-6|-5|-4|-3|-2|-1|0 |1 |2 |3 |4 |5 |6 |7
1 2009-10-17 17:38:32.590 |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |0 |0 |0 |0 |0
2 2009-10-19 00:37:23.067 |0 |0 |0 |0 |0 |1 |1 |0 |1 |0 |0 |0 |0 |0 |0
3 2009-10-20 08:37:14.143 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
4 2009-10-21 18:07:51.247 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
5 2009-10-22 21:25:24.483 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
รหัส
badges = ["A", "B", "C"]
for badge in badges:
res.iloc[:,2:].mean().plot(kind='line', label = badge)
เอาต์พุต
แก้ไข (พล็อตสำหรับกราฟเดียวที่มี Standard Deviation)
res.iloc[:,2:].mean().plot(kind='line', label = 'A')
plt.errorbar(x = res.columns.values[:-1], y = res.iloc[:,2:].mean(),yerr = res.iloc[:,2:].std())
การเรียกใช้รหัสนี้ก่อให้เกิดข้อผิดพลาดต่อไปนี้:
TypeError: 'value' must be an instance of str or bytes, not a int
คำตอบ
gherka Oct 10 2020 at 17:50
หากคุณต้องการสร้างเส้นและแถบข้อผิดพลาดในลูปคุณสามารถใช้plt.errorbar()ภายในลูปได้ตามปกติ แต่การใช้seabornจะง่ายกว่ามากหากคุณสามารถรับข้อมูลของคุณในรูปแบบที่เหมาะสม
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.concat([
pd.DataFrame(np.random.randint(0,2, (5, 14))).assign(badge="A"),
pd.DataFrame(np.random.randint(0,2, (5, 14))).assign(badge="B"),
])
plt.figure(figsize=(10, 5))
badges = ["A", "B"]
colors = ["teal", "firebrick"]
for i, badge in enumerate(badges):
sub_df = df[df["badge"]==badge]
sub_df.iloc[:,:-1].mean().plot(kind='line', label=badge, color=colors[i])
plt.errorbar(
sub_df.columns.values[:-1] + (i*0.1), # offset the second error bar a bit
sub_df.iloc[:,:-1].mean(),
yerr=sub_df.iloc[:,:-1].std(),
fmt='|', ecolor='grey', elinewidth=1
);