-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_xarray.py
More file actions
70 lines (57 loc) · 2.07 KB
/
plot_xarray.py
File metadata and controls
70 lines (57 loc) · 2.07 KB
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
import xarray as xr
import matplotlib.pyplot as plt
import os
DATA_PATH = "data/temperature_data.nc"
def generate_plots():
"""
Generate multiple plots from an Xarray dataset using Matplotlib (PyPlot).
Plots include:
- Line plot
- Histogram
- Scatter plot
- Rolling average trend plot
"""
if not os.path.exists(DATA_PATH):
raise FileNotFoundError("Dataset not found. Run dataset generator first.")
os.makedirs("plots", exist_ok=True)
# Load dataset
ds = xr.open_dataset(DATA_PATH)
# ---------------- Line Plot ----------------
plt.figure(figsize=(8, 5))
ds.temperature.plot()
plt.title("Monthly Temperature Variation")
plt.xlabel("Time")
plt.ylabel("Temperature (°C)")
plt.tight_layout()
plt.savefig("plots/line_plot.png")
plt.close()
# ---------------- Histogram ----------------
plt.figure(figsize=(8, 5))
ds.temperature.plot.hist(bins=6)
plt.title("Temperature Distribution")
plt.xlabel("Temperature (°C)")
plt.tight_layout()
plt.savefig("plots/histogram.png")
plt.close()
# ---------------- Scatter Plot ----------------
plt.figure(figsize=(8, 5))
plt.scatter(ds.time.values, ds.temperature.values)
plt.title("Temperature Scatter Plot")
plt.xlabel("Time")
plt.ylabel("Temperature (°C)")
plt.tight_layout()
plt.savefig("plots/scatter_plot.png")
plt.close()
# ---------------- Rolling Average Plot (Advanced) ----------------
plt.figure(figsize=(8, 5))
rolling_temp = ds.temperature.rolling(time=3, center=True).mean()
plt.plot(ds.time, ds.temperature, label="Actual Temperature")
plt.plot(ds.time, rolling_temp, linestyle="--", label="3-Month Rolling Average")
plt.title("Temperature Trend with Rolling Average")
plt.xlabel("Time")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.tight_layout()
plt.savefig("plots/rolling_avg_plot.png")
plt.close()
print("All plots successfully generated and saved in 'plots/' folder.")