Skip to content

Instantly share code, notes, and snippets.

@partrita
Created December 24, 2024 06:29
Show Gist options
  • Save partrita/a5a6f63494d4978c99307b55e534df4c to your computer and use it in GitHub Desktop.
Save partrita/a5a6f63494d4978c99307b55e534df4c to your computer and use it in GitHub Desktop.
Snippet for strip and errorbar mean plot.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from typing import Tuple
def plot_data(combined_tidy_df: pd.DataFrame, source: str, title: str, figsize: Tuple[int, int]) -> None:
"""
특정 소스에 대한 데이터를 평균, 표준편차, 개별 데이터 포인트와 함께 플롯합니다.
Args:
combined_tidy_df (pd.DataFrame): 데이터를 포함하는 결합된 tidy DataFrame.
source (str): 필터링할 특정 소스.
title (str): 플롯의 제목.
figsize (Tuple[int, int]): 그림의 크기.
Returns:
None
"""
# 특정 소스에 대해 필터링
df = combined_tidy_df[combined_tidy_df["Source"] == source]
# 평균과 표준편차 계산
summary_df = df.groupby("Time")["Value"].agg(mean="mean", sd="std").reset_index()
# 플롯팅
plt.figure(figsize=figsize)
# 개별 데이터 포인트를 위한 스트립플롯
sns.stripplot(data=df, x="Time", y="Value", color="black", alpha=0.5, jitter=True)
# 평균값을 위한 포인트플롯
sns.pointplot(
data=summary_df, x="Time", y="mean",
linestyle="none", # 포인트 사이의 선 제거
markers="_", markersize=20, color="black"
)
# 사용자 정의 두께의 오차 막대 추가
plt.errorbar(
summary_df["Time"], summary_df["mean"], yerr=summary_df["sd"],
fmt='none', ecolor="black", capsize=5, elinewidth=1. # 두께 조정
)
# y=0에 수평 참조선 추가
plt.axhline(0, color='black', linestyle='--', linewidth=1)
# 레이블과 제목 설정
plt.title(title, fontsize=12)
plt.xlabel('Time (month)', fontsize=10)
plt.ylabel('% Difference', fontsize=10)
plt.ylim(-0.05, 0.2)
plt.tight_layout()
plt.show()
# 함수 사용 예시
# plot_data(combined_tidy_df, "AG099 5C", 'AG099 (5±3°C)', (5, 4))
# plot_data(combined_tidy_df, "AG034 5C", 'AG034 (5±3°C)', (4, 4))
# plot_data(combined_tidy_df, "AG099 25C", 'AG099 (25±3°C)', (3, 4))
@partrita
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment