Import Library
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Load Data
df = pd.read_csv("Rangkaian waktu Wilayah • Wilayah berdasarkan kelas • 1990 - 2024.csv")
df_filtered = df[df['Tingkat 2'].isin(['Formasi Hutan', 'Sawit'])].copy()
Set Periode
years = ['2000', '2005', '2010', '2015', '2020', '2024']Persiapkan data biar tahun menjadi index (Sumbu X)
data = df_filtered.set_index('Tingkat 2')[years].astype(float).T
data.index = pd.to_numeric(data.index)Setting Warna
colors = {'Formasi Hutan': '#2ca02c', 'Sawit': '#9467bd'}Set Sumbu
ax.set_xlim(1999, 2025)
ax.set_ylim(0, data.max().max() * 1.1)
ax.set_xticks([2000, 2005, 2010, 2015, 2020, 2024])
ax.set_xlabel('Tahun', fontsize=12, fontweight='bold')
ax.set_ylabel('Luas (Ha)', fontsize=12, fontweight='bold')
ax.set_title('PERBANDINGAN TEMPORAL LUAS FORMASI HUTAN DAN KEBUN SAWIT DI ACEH TAMIANG 2000-2014', fontsize=12, fontweight='bold')
Seting Garis
line_hutan, = ax.plot([], [], color=colors['Formasi Hutan'], label='Formasi Hutan', linewidth=4, marker='o', markersize=8)
line_sawit, = ax.plot([], [], color=colors['Sawit'], label='Sawit', linewidth=4, marker='o', markersize=8)
Label teks luas di ujung garis
text_hutan = ax.text(0, 0, '', color=colors['Formasi Hutan'], fontweight='bold', va='bottom', ha='right')
text_sawit = ax.text(0, 0, '', color=colors['Sawit'], fontweight='bold', va='top', ha='right')
ax.legend(loc='center right')
ax.grid(True, linestyle='--', alpha=0.5)
Memunculkan data tahun per tahun untuk animasi
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
def update(frame):
curr_years = data.index[:frame+1]
line_hutan.set_data(curr_years, data.loc[curr_years, 'Formasi Hutan'])
line_sawit.set_data(curr_years, data.loc[curr_years, 'Sawit'])
if len(curr_years) > 0:
last_year = curr_years[-1]
val_h = data.loc[last_year, 'Formasi Hutan']
val_s = data.loc[last_year, 'Sawit']
text_hutan.set_position((last_year, val_h + 1000))
text_hutan.set_text(f'{val_h:,.0f}')
text_sawit.set_position((last_year, val_s - 2000))
text_sawit.set_text(f'{val_s:,.0f}')
return line_hutan, line_sawit, text_hutan, text_sawit
Eksekusi animasi sama simpen
ani = animation.FuncAnimation(fig, update, frames=len(years), interval=800, blit=True)
ani.save('grafik_garis_temporal.gif', writer='pillow', fps=1.5)
from IPython.display import HTML, display
display(HTML(ani.to_jshtml()))
plt.close()