{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "e11c7be7-e915-46fa-8a6d-34a76acd658b", "metadata": {}, "outputs": [], "source": [ "this given code takes input from path : Bihar_Y_Precipitation_CHIRPS.tif and gives output \"Bihar_Y_Precipitation_GT_geotif.tif\" but now we also wants to take its shape file shpfile = \"SateMask/gadm41_IND_1.shp\" ,and then also want to print the number of missing values ,total number of values and non-missing values, also want min and max rainfall in each bands ,ans=d against each image we want histogram of how many values lie in each category like scarcity ,deficit,NORMAL,excess,large excess etc and also want a together comparison .can you please do it please .you can take help from this code import os\n", "import rasterio\n", "import numpy as np\n", "import geopandas as gpd\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "from matplotlib.colors import ListedColormap\n", "from matplotlib.patches import Patch\n", "from rasterio.features import geometry_mask\n", "\n", "# -----------------------------------------------------------------------------\n", "# 1) FILE PATHS\n", "# -----------------------------------------------------------------------------\n", "raw_tiff = \"Bihar_Y_Precipitation_CHIRPS.tif\"\n", "cat_tiff = \"Bihar_Y_Precipitation_GT_geotif.tif\"\n", "shpfile = \"SateMask/gadm41_IND_1.shp\"\n", "for p in (raw_tiff, cat_tiff, shpfile):\n", " if not os.path.isfile(p):\n", " raise FileNotFoundError(f\"Cannot find {p!r}\")\n", "\n", "# -----------------------------------------------------------------------------\n", "# 2) LOAD BIHAR SHAPE & BUILD MASK\n", "# -----------------------------------------------------------------------------\n", "gdf = gpd.read_file(shpfile)\n", "gdf_bihar = gdf[gdf[\"NAME_1\"].str.lower() == \"bihar\"].copy()\n", "if gdf_bihar.empty:\n", " raise ValueError(\"No 'Bihar' feature in shapefile\")\n", "\n", "with rasterio.open(raw_tiff) as ref:\n", " transform, crs = ref.transform, ref.crs\n", " H, W = ref.height, ref.width\n", " bounds = ref.bounds\n", "\n", "if gdf_bihar.crs != crs:\n", " gdf_bihar = gdf_bihar.to_crs(crs)\n", "\n", "# use union_all() instead of deprecated unary_union\n", "unioned_geom = gdf_bihar.geometry.union_all()\n", "\n", "mask = geometry_mask(\n", " [unioned_geom],\n", " transform=transform,\n", " invert=True,\n", " out_shape=(H, W)\n", ")\n", "\n", "# -----------------------------------------------------------------------------\n", "# 3) READ RASTERS\n", "# -----------------------------------------------------------------------------\n", "with rasterio.open(raw_tiff) as src:\n", " pr_raw = src.read().astype(np.float32) # (25, H, W)\n", "with rasterio.open(cat_tiff) as src:\n", " pr_cat = src.read().astype(np.int8) # (25, H, W)\n", "assert pr_raw.shape[0] == pr_cat.shape[0] == 25\n", "\n", "# -----------------------------------------------------------------------------\n", "# 4) LABELS & COLORS\n", "# -----------------------------------------------------------------------------\n", "years = [2020, 2021, 2022, 2023, 2024]\n", "months = [\"June\", \"July\", \"August\", \"September\"]\n", "labels = [f\"{years[i//4]} {months[i%4]}\" for i in range(20)]\n", "\n", "cat_colors = [\"#79d151\", \"#22a784\", \"#29788e\", \"#404387\", \"#440154\"]\n", "cmap = ListedColormap(cat_colors)\n", "cat_names = [\n", " \"Scarcity (<0.4×)\",\n", " \"Deficit (0.4–0.8×)\",\n", " \"Normal (0.8–1.2×)\",\n", " \"Excess (1.2–1.6×)\",\n", " \"LargeExcess (≥1.6×)\"\n", "]\n", "legend_handles = [\n", " Patch(facecolor=cat_colors[i], edgecolor=\"black\", label=cat_names[i])\n", " for i in range(5)\n", "]\n", "\n", "# -----------------------------------------------------------------------------\n", "# 5) 5×8 PANEL OF MAP + HISTOGRAM\n", "# -----------------------------------------------------------------------------\n", "fig, axes = plt.subplots(\n", " nrows=5, ncols=8,\n", " figsize=(28, 20), dpi=120,\n", " constrained_layout=True\n", ")\n", "fig.suptitle(\n", " \"Bihar 2020–2024: Precipitation Categories with Min/Max Rainfall\",\n", " fontsize=22, y=1.02\n", ")\n", "\n", "for yi in range(5):\n", " for mi in range(4):\n", " idx = yi*4 + mi\n", " ax_map = axes[yi, mi*2]\n", " ax_hist = axes[yi, mi*2+1]\n", "\n", " # compute min/max over Bihar\n", " vals = pr_raw[idx][mask]\n", " mn, mx = np.nanmin(vals), np.nanmax(vals)\n", "\n", " # draw category map\n", " layer = pr_cat[idx]\n", " disp = np.where(mask, layer, np.nan)\n", " ax_map.imshow(\n", " disp, cmap=cmap, vmin=0, vmax=4,\n", " extent=[bounds.left, bounds.right, bounds.bottom, bounds.top],\n", " origin=\"upper\"\n", " )\n", " ax_map.set_title(\n", " f\"{labels[idx]}\\nmin={mn:.1f} mm max={mx:.1f} mm\",\n", " fontsize=12, loc=\"left\"\n", " )\n", " ax_map.axis(\"off\")\n", "\n", " # draw histogram\n", " counts = [(layer[mask] == i).sum() for i in range(5)]\n", " ax_hist.bar(\n", " range(5), counts,\n", " color=cat_colors, edgecolor=\"black\"\n", " )\n", " ax_hist.set_xticks(range(5))\n", " ax_hist.set_xticklabels(cat_names, rotation=45,\n", " ha=\"right\", fontsize=8)\n", " if mi == 0:\n", " ax_hist.set_ylabel(\"Pixels\", fontsize=10)\n", " else:\n", " ax_hist.set_yticks([])\n", " ax_hist.set_ylim(0, max(counts)*1.1)\n", "\n", "fig.legend(\n", " handles=legend_handles,\n", " labels=cat_names,\n", " loc=\"lower center\",\n", " ncol=3,\n", " frameon=True,\n", " title=\"Categories\",\n", " fontsize=12,\n", " title_fontsize=14,\n", " bbox_to_anchor=(0.5, -0.02)\n", ")\n", "plt.show()\n", "\n", "# -----------------------------------------------------------------------------\n", "# 6) STACKED-BAR “CATEGORY DISTRIBUTION BY MONTH”\n", "# -----------------------------------------------------------------------------\n", "all_counts = []\n", "for idx in range(20):\n", " layer = pr_cat[idx]\n", " counts = [(layer[mask] == i).sum() for i in range(5)]\n", " all_counts.append(counts)\n", "\n", "df = pd.DataFrame(\n", " all_counts,\n", " columns=cat_names,\n", " index=labels\n", ")\n", "\n", "fig, ax = plt.subplots(figsize=(16, 6))\n", "bottom = np.zeros(len(df))\n", "for cat in cat_names:\n", " ax.bar(\n", " df.index, df[cat],\n", " bottom=bottom,\n", " color=cat_colors[cat_names.index(cat)],\n", " edgecolor=\"black\",\n", " label=cat\n", " )\n", " bottom += df[cat].values\n", "\n", "ax.set_xticks(df.index)\n", "ax.set_xticklabels(df.index, rotation=45, ha=\"right\")\n", "ax.set_ylabel(\"Pixel Count\")\n", "ax.set_title(\"Precipitation Category Distribution by Month\", fontsize=16)\n", "ax.legend(title=\"Category\", bbox_to_anchor=(1.02, 1), loc=\"upper left\")\n", "plt.tight_layout()\n", "plt.show() ." ] }, { "cell_type": "code", "execution_count": null, "id": "3f22394e-767f-4fcb-8b5f-c614b97c05ca", "metadata": {}, "outputs": [], "source": [ "##map and histogram" ] }, { "cell_type": "code", "execution_count": null, "id": "b022ad75-71e0-4840-b8a8-b0dadd25f5c7", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "import os\n", "import rasterio\n", "import numpy as np\n", "import geopandas as gpd\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "from matplotlib.colors import ListedColormap\n", "from matplotlib.patches import Patch\n", "from rasterio.features import geometry_mask\n", "\n", "# -----------------------------------------------------------------------------\n", "# 1) FILE PATHS\n", "# -----------------------------------------------------------------------------\n", "raw_tiff = \"Bihar_Y_Precipitation_CHIRPS.tif\"\n", "cat_tiff = \"Bihar_Y_Precipitation_GT_geotif.tif\"\n", "shpfile = \"SateMask/gadm41_IND_1.shp\"\n", "for p in (raw_tiff, cat_tiff, shpfile):\n", " if not os.path.isfile(p):\n", " raise FileNotFoundError(f\"Cannot find {p!r}\")\n", "\n", "# -----------------------------------------------------------------------------\n", "# 2) LOAD BIHAR SHAPE & BUILD MASK\n", "# -----------------------------------------------------------------------------\n", "gdf = gpd.read_file(shpfile)\n", "gdf_bihar = gdf[gdf[\"NAME_1\"].str.lower() == \"bihar\"].copy()\n", "if gdf_bihar.empty:\n", " raise ValueError(\"No 'Bihar' feature in shapefile\")\n", "\n", "with rasterio.open(raw_tiff) as ref:\n", " transform, crs = ref.transform, ref.crs\n", " H, W = ref.height, ref.width\n", " bounds = ref.bounds\n", "\n", "if gdf_bihar.crs != crs:\n", " gdf_bihar = gdf_bihar.to_crs(crs)\n", "\n", "# use union_all() instead of deprecated unary_union\n", "unioned_geom = gdf_bihar.geometry.union_all()\n", "\n", "mask = geometry_mask(\n", " [unioned_geom],\n", " transform=transform,\n", " invert=True,\n", " out_shape=(H, W)\n", ")\n", "\n", "# -----------------------------------------------------------------------------\n", "# 3) READ RASTERS\n", "# -----------------------------------------------------------------------------\n", "with rasterio.open(raw_tiff) as src:\n", " pr_raw = src.read().astype(np.float32) # (25, H, W)\n", "with rasterio.open(cat_tiff) as src:\n", " pr_cat = src.read().astype(np.int8) # (25, H, W)\n", "assert pr_raw.shape[0] == pr_cat.shape[0] == 25\n", "\n", "# -----------------------------------------------------------------------------\n", "# 4) LABELS & COLORS\n", "# -----------------------------------------------------------------------------\n", "years = [2020, 2021, 2022, 2023, 2024]\n", "months = [\"June\", \"July\", \"August\", \"September\"]\n", "labels = [f\"{years[i//4]} {months[i%4]}\" for i in range(20)]\n", "\n", "cat_colors = [\"#79d151\", \"#22a784\", \"#29788e\", \"#404387\", \"#440154\"]\n", "cmap = ListedColormap(cat_colors)\n", "cat_names = [\n", " \"Scarcity (<0.4×)\",\n", " \"Deficit (0.4–0.8×)\",\n", " \"Normal (0.8–1.2×)\",\n", " \"Excess (1.2–1.6×)\",\n", " \"LargeExcess (≥1.6×)\"\n", "]\n", "legend_handles = [\n", " Patch(facecolor=cat_colors[i], edgecolor=\"black\", label=cat_names[i])\n", " for i in range(5)\n", "]\n", "\n", "# -----------------------------------------------------------------------------\n", "# 5) 5×8 PANEL OF MAP + HISTOGRAM\n", "# -----------------------------------------------------------------------------\n", "fig, axes = plt.subplots(\n", " nrows=5, ncols=8,\n", " figsize=(28, 20), dpi=120,\n", " constrained_layout=True\n", ")\n", "fig.suptitle(\n", " \"Bihar 2020–2024: Precipitation Categories with Min/Max Rainfall\",\n", " fontsize=22, y=1.02\n", ")\n", "\n", "for yi in range(5):\n", " for mi in range(4):\n", " idx = yi*4 + mi\n", " ax_map = axes[yi, mi*2]\n", " ax_hist = axes[yi, mi*2+1]\n", "\n", " # compute min/max over Bihar\n", " vals = pr_raw[idx][mask]\n", " mn, mx = np.nanmin(vals), np.nanmax(vals)\n", "\n", " # draw category map\n", " layer = pr_cat[idx]\n", " disp = np.where(mask, layer, np.nan)\n", " ax_map.imshow(\n", " disp, cmap=cmap, vmin=0, vmax=4,\n", " extent=[bounds.left, bounds.right, bounds.bottom, bounds.top],\n", " origin=\"upper\"\n", " )\n", " ax_map.set_title(\n", " f\"{labels[idx]}\\nmin={mn:.1f} mm max={mx:.1f} mm\",\n", " fontsize=12, loc=\"left\"\n", " )\n", " ax_map.axis(\"off\")\n", "\n", " # draw histogram\n", " counts = [(layer[mask] == i).sum() for i in range(5)]\n", " ax_hist.bar(\n", " range(5), counts,\n", " color=cat_colors, edgecolor=\"black\"\n", " )\n", " ax_hist.set_xticks(range(5))\n", " ax_hist.set_xticklabels(cat_names, rotation=45,\n", " ha=\"right\", fontsize=8)\n", " if mi == 0:\n", " ax_hist.set_ylabel(\"Pixels\", fontsize=10)\n", " else:\n", " ax_hist.set_yticks([])\n", " ax_hist.set_ylim(0, max(counts)*1.1)\n", "\n", "fig.legend(\n", " handles=legend_handles,\n", " labels=cat_names,\n", " loc=\"lower center\",\n", " ncol=3,\n", " frameon=True,\n", " title=\"Categories\",\n", " fontsize=12,\n", " title_fontsize=14,\n", " bbox_to_anchor=(0.5, -0.02)\n", ")\n", "plt.show()\n", "\n", "# -----------------------------------------------------------------------------\n", "# 6) STACKED-BAR “CATEGORY DISTRIBUTION BY MONTH”\n", "# -----------------------------------------------------------------------------\n", "all_counts = []\n", "for idx in range(20):\n", " layer = pr_cat[idx]\n", " counts = [(layer[mask] == i).sum() for i in range(5)]\n", " all_counts.append(counts)\n", "\n", "df = pd.DataFrame(\n", " all_counts,\n", " columns=cat_names,\n", " index=labels\n", ")\n", "\n", "fig, ax = plt.subplots(figsize=(16, 6))\n", "bottom = np.zeros(len(df))\n", "for cat in cat_names:\n", " ax.bar(\n", " df.index, df[cat],\n", " bottom=bottom,\n", " color=cat_colors[cat_names.index(cat)],\n", " edgecolor=\"black\",\n", " label=cat\n", " )\n", " bottom += df[cat].values\n", "\n", "ax.set_xticks(df.index)\n", "ax.set_xticklabels(df.index, rotation=45, ha=\"right\")\n", "ax.set_ylabel(\"Pixel Count\")\n", "ax.set_title(\"Precipitation Category Distribution by Month\", fontsize=16)\n", "ax.legend(title=\"Category\", bbox_to_anchor=(1.02, 1), loc=\"upper left\")\n", "plt.tight_layout()\n", "plt.show()\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5 }