File size: 8,428 Bytes
64999ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa307e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64999ea
 
fa307e3
 
64999ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv('src/addiction_population_data.csv')

def eda1():
    """
    Visualisasi distribusi target (has_health_issues) dan menampilkan proporsi
    """
    # Buat figure
    fig, ax = plt.subplots(figsize=(6, 4))
    
    # Buat countplot
    sns.countplot(
        x='has_health_issues',
        data=df,
        palette='husl',
        ax=ax
    )
    
    # Atur judul dan label
    ax.set_title('Distribusi Status Kesehatan', fontsize=14, pad=15)
    ax.set_xlabel('Status Kesehatan (0=Tidak, 1=Ya)', fontsize=12)
    ax.set_ylabel('Jumlah Sampel', fontsize=12)
    
    # Hitung dan simpan proporsi
    proporsi = df['has_health_issues'].value_counts(normalize=True)
    
    # Tambahkan anotasi jumlah di atas setiap bar
    for p in ax.patches:
        ax.annotate(
            f'{p.get_height()}',
            (p.get_x() + p.get_width()/2., p.get_height()),
            ha='center',
            va='center',
            xytext=(0, 10),
            textcoords='offset points',
            fontsize=11
        )
    # Tambahkan grid
    ax.grid(axis='y', linestyle='--', alpha=0.3)
    
    # Optimalkan layout
    plt.tight_layout()
    
    # Tampilkan figure dan proporsi
    plt.show()
    print("Proporsi:\n", proporsi)
    
    return fig

def eda2():
    """
    Visualisasi distribusi usia berdasarkan status kesehatan
    """
    # Buat figure
    fig, ax = plt.subplots(figsize=(8, 5))
    
    # Buat boxplot
    sns.boxplot(
        x='has_health_issues',
        y='age',
        data=df,
        palette='husl',
        ax=ax,
        showmeans=True,
        meanprops={"marker":"o", "markerfacecolor":"white", "markeredgecolor":"black"}
    )
    
    # Atur judul dan label
    ax.set_title('Distribusi Usia berdasarkan Status Kesehatan', fontsize=14, pad=15)
    ax.set_xlabel('Memiliki Masalah Kesehatan', fontsize=12)
    ax.set_ylabel('Usia', fontsize=12)
    
    # Format x-axis labels
    ax.set_xticklabels(['Tidak', 'Ya'])
    
    # Tambahkan grid
    ax.grid(axis='y', linestyle='--', alpha=0.3)
    
    # Optimalkan layout
    plt.tight_layout()
    
    return fig

def eda3():
    # def eda3(df, figsize=(10, 6), palette='husl', title=None):
    # Buat figure
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # Buat KDE plot
    sns.kdeplot(
        data=df,
        x='annual_income_usd',
        hue='has_health_issues',
        fill=True,
        common_norm=False,
        alpha=0.5,
        palette='husl',
        ax=ax
    )
    
    # Atur judul dan label
    plot_title = 'Distribusi Pendapatan Tahunan berdasarkan Status Kesehatan'
    ax.set_title(plot_title, fontsize=14, pad=15)
    ax.set_xlabel('Pendapatan Tahunan (USD)', fontsize=12)
    ax.set_ylabel('Density', fontsize=12)
    
    # Format legenda
    ax.legend(
        title='Memiliki Masalah Kesehatan',
        labels=['Tidak', 'Ya'],
        frameon=True,
        framealpha=0.8
    )
    
    # Tambahkan grid
    ax.grid(axis='both', linestyle='--', alpha=0.3)
    
    # Optimalkan layout
    plt.tight_layout()
    
    return fig

def eda4():
    # Buat figure dengan 2 subplot
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
    
    # Plot 1: Merokok per hari
    sns.boxplot(
        x='has_health_issues',
        y='smokes_per_day',
        data=df,
        palette='husl',
        ax=ax1,
        showmeans=True,
        meanprops={"marker":"o", "markerfacecolor":"white", "markeredgecolor":"black"}
    )
    ax1.set_title('Konsumsi Rokok per Hari berdasarkan Status Kesehatan', fontsize=14, pad=15)
    ax1.set_xlabel('Memiliki Masalah Kesehatan', fontsize=12)
    ax1.set_ylabel('Jumlah Rokok per Hari', fontsize=12)
    ax1.set_xticklabels(['Tidak', 'Ya'])
    ax1.grid(axis='y', linestyle='--', alpha=0.3)
    
    # Plot 2: Minum per minggu
    sns.boxplot(
        x='has_health_issues',
        y='drinks_per_week',
        data=df,
        palette='husl',
        ax=ax2,
        showmeans=True,
        meanprops={"marker":"o", "markerfacecolor":"white", "markeredgecolor":"black"}
    )
    ax2.set_title('Konsumsi Alkohol per Minggu berdasarkan Status Kesehatan', fontsize=14, pad=15)
    ax2.set_xlabel('Memiliki Masalah Kesehatan', fontsize=12)
    ax2.set_ylabel('Jumlah Minuman per Minggu', fontsize=12)
    ax2.set_xticklabels(['Tidak', 'Ya'])
    ax2.grid(axis='y', linestyle='--', alpha=0.3)
    
    # Optimalkan layout
    plt.tight_layout()
    
    return fig

def eda5():
    # Pilih fitur numerik
    num_features = [
        'age', 'annual_income_usd', 'smokes_per_day', 'drinks_per_week',
        'age_started_smoking', 'age_started_drinking',
        'attempts_to_quit_smoking', 'attempts_to_quit_drinking', 
        'sleep_hours', 'bmi'
    ]
    
    # Hitung korelasi
    corr = df[num_features + ['has_health_issues']].corr()
    
    # Buat figure dan axes
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # Buat heatmap dengan berbagai pengaturan visual
    heatmap = sns.heatmap(
        corr,
        annot=True,
        cmap='coolwarm',
        center=0,
        fmt=".2f",  # Format 2 digit desimal
        linewidths=0.5,
        linecolor='white',
        square=True,
        cbar_kws={"shrink": 0.8},
        ax=ax
    )
    # Atur judul dan font
    ax.set_title(
        'Korelasi Fitur Numerik dengan Health Issues',
        fontsize=14,
        pad=20
    )
    
    # Rotasi label x-axis
    plt.xticks(rotation=45, ha='right')
    
    # Optimalkan layout
    plt.tight_layout()
    
    return fig

def eda6():
    # Hitung proporsi
    gender_rate = df.groupby('gender')['has_health_issues'].mean().reset_index()
    
    # Buat figure
    fig, ax = plt.subplots(figsize=(8, 5))
    # Buat barplot
    barplot = sns.barplot(
        x='gender', 
        y='has_health_issues', 
        data=gender_rate,
        ax=ax,
        palette='pastel',  # Warna yang lebih soft
        edgecolor='black'  # Garis tepi untuk kontras
    )
    # Atur judul dan label
    ax.set_title('Proporsi Health Issues Berdasarkan Gender', fontsize=14, pad=20)
    ax.set_xlabel('Gender', fontsize=12)
    ax.set_ylabel('Proporsi Health Issues', fontsize=12)
    
    # Atur y-axis limit
    ax.set_ylim(0, 1)
    
    # Tambahkan nilai persentase di atas setiap bar
    for p in ax.patches:
        height = p.get_height()
        ax.text(
            p.get_x() + p.get_width()/2.,
            height + 0.02,
            f'{height:.1%}',
            ha='center',
            va='bottom',
            fontsize=12
        )
    # Tambahkan grid untuk kemudahan membaca
    ax.grid(axis='y', linestyle='--', alpha=0.7)
    
    # Optimalkan layout
    plt.tight_layout()
    
    return fig

def eda7():
    # Create figure with two subplots
    fig, axes = plt.subplots(2, 1, figsize=(10, 12))
    
    # Plot 1: Countplot
    sns.countplot(
        x='social_support', 
        hue='has_health_issues', 
        data=df, 
        ax=axes[0],
        order=['Weak', 'Moderate', 'Strong']  # Ensure consistent order
    )
    axes[0].set_title('Distribusi Health Issues Berdasarkan Social Support', fontsize=14)
    axes[0].set_xlabel('Tingkat Social Support', fontsize=12)
    axes[0].set_ylabel('Jumlah Sampel', fontsize=12)
    axes[0].legend(title='Health Issues', loc='best')
    axes[0].grid(axis='y', linestyle='--', alpha=0.7)
    
    # Plot 2: Proportion plot
    prop = df.groupby('social_support')['has_health_issues'].mean().reset_index()
    
    sns.barplot(
        x='social_support',
        y='has_health_issues',
        data=prop,
        order=['Weak', 'Moderate', 'Strong'],
        ax=axes[1],
        palette='viridis'
    )
    axes[1].set_title('Proporsi Health Issues per Tingkat Social Support', fontsize=14)
    axes[1].set_xlabel('Tingkat Social Support', fontsize=12)
    axes[1].set_ylabel('Proporsi Health Issues', fontsize=12)
    axes[1].set_ylim(0, 1)
    
    # Menambahkan label persentase di atas setiap bar
    for p in axes[1].patches:
        axes[1].annotate(
            f'{p.get_height():.2%}', 
            (p.get_x() + p.get_width() / 2., p.get_height()),
            ha='center', va='center', 
            xytext=(0, 10), 
            textcoords='offset points',
            fontsize=10
        )
    
    axes[1].grid(axis='y', linestyle='--', alpha=0.7)
    
    # Adjust layout
    plt.tight_layout(pad=3.0)
    return fig