General Visualization

General Visualization#

# --- Packages ---
## General Packages
import pandas as pd
import xarray as xr
import numpy as np
import os
import ipynbname

## GeoCAT
import geocat.comp as gccomp
import geocat.viz as gv
import geocat.viz.util as gvutil

## Visualization
import cmaps  
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import shapely.geometry as sgeom

## MatPlotLib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches
import matplotlib.dates as mdates

from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.ticker import MultipleLocator
# --- Automated output filename ---
def get_filename():
    try:
        # Will fail when __file__ is undefined (e.g., in notebooks)
        filename = os.path.splitext(os.path.basename(__file__))[0]
    except NameError:
        try:
            # Will fail during non-interactive builds
            import ipynbname
            nb_path = ipynbname.path()
            filename = os.path.splitext(os.path.basename(str(nb_path)))[0]
        except Exception:
            # Fallback during Jupyter Book builds or other headless execution
            filename = "template_timeseries_bar"
    return filename

fnFIG = get_filename() + ".png"
print(f"Figure filename: {fnFIG}")
Figure filename: template_timeseries_bar.png
# --- DATA ANALYSIS ---

# Replace this block
ystr, yend = 1950, 2020
years = np.arange(ystr, yend + 1)
values = np.random.randn(len(years))  # or use np.random.rand() for [0, 1] range
dat = xr.DataArray(values, coords={"year": years},
    dims=["year"], name="dummy data")
print(dat)
<xarray.DataArray 'dummy data' (year: 71)> Size: 568B
array([-0.4843188 ,  2.40261393, -0.46332516,  0.39776257,  0.67061948,
        0.21240865, -1.06112689, -0.86353084,  1.16847029, -0.1397476 ,
       -0.44768869, -0.73648224,  0.08551056,  1.78905037, -0.05607742,
       -0.43569478, -0.03836825, -0.93586557, -0.3978415 , -0.86931701,
        0.89609499, -1.24610384,  0.36530542,  0.28216164, -2.21964377,
       -0.487093  ,  0.38064413,  0.8263173 ,  0.92659117,  0.48201554,
       -0.30997155, -0.92888756, -0.35334767,  0.84858132,  0.04973996,
        0.39921531, -0.62242991, -0.61562867, -0.02264409, -2.34382214,
        0.4942993 , -0.36424873, -2.2234155 ,  1.43527121,  1.09667618,
       -0.22106739, -1.1591151 , -1.13491347, -1.60483025, -0.16524129,
       -0.04706309,  2.16223059, -1.01814492, -0.70738492, -1.66138667,
        0.28609912,  0.48430743, -0.52239555,  0.53166277,  1.1904657 ,
       -0.25438374, -0.97883972, -0.38050275,  1.44993864,  0.51302878,
       -0.2772847 , -1.0908509 ,  0.16344594,  0.95479586,  1.11094284,
       -0.74651494])
Coordinates:
  * year     (year) int64 568B 1950 1951 1952 1953 1954 ... 2017 2018 2019 2020
# --- FIGURE PLOT ---
# Layout setting
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 12))
col = cmaps.amwg  # Use the AMWG colormap

axes = axes.flatten()  # 🔑 Make it a 1D list of axes

# --- Plot 1 ---
ip = 0
axes[ip].plot(dat.year, dat, label="Label", color=col.colors[4-2], linewidth=2)
gvutil.set_titles_and_labels(axes[ip],
    maintitle="Main title",
    lefttitle="(a) Left Title",
    righttitle="Right Title",
    ylabel="Y title",
    xlabel="X title",
    maintitlefontsize=14,  # Adjust main title font size
    lefttitlefontsize=12,  # Set left title font size
    righttitlefontsize=12,  # Set left title font size
    labelfontsize=10  # Set y-label font size
)

# --- Plot 2 ---
ip = 1
axes[ip].bar(dat.year, dat, label="Label", color=col.colors[4-2], linewidth=2)
gvutil.set_titles_and_labels(axes[ip],
    lefttitle="(b) Second Plot",
)

# --- Plot 3 ---
ip = 2
axes[ip].plot(dat.year, dat, marker="o", linestyle="None", markersize=6)
gvutil.set_titles_and_labels(axes[ip],
    lefttitle="(c) Third Plot",
)


# Apply the overall figure title
fig.suptitle("Figure Title", fontsize=16, fontweight="bold")

# --- OUTPUT ---
plt.tight_layout()
plt.savefig(fnFIG, dpi=300, bbox_inches="tight")
plt.show()
../_images/2f4c924c93df43f12bfab8c2628eccab86679e33cac2a3151a34738a020b8166.png