Plotting & Visualization¶
The tit.plotting module provides matplotlib-based visualization functions used by the analysis, optimization, and reporting pipelines. All functions are headless-safe and work in Docker/CI environments without a display server.
graph LR
ANALYZER[Analyzer] --> PLOTS[tit.plotting]
STATS[Stats Module] --> PLOTS
REPORTING[Report Generators] --> PLOTS
PLOTS --> PDF[PDF Figures]
PLOTS --> PNG[PNG / base64 Images]
style PLOTS fill:#2d5a27,stroke:#4a8,color:#fff
Focality Histograms¶
plot_whole_head_roi_histogram¶
Generates a whole-head field distribution histogram with per-bin ROI contribution color coding. Includes focality cutoff lines, an optional mean ROI field marker, and a summary statistics box.
from tit.plotting import plot_whole_head_roi_histogram
output_path = plot_whole_head_roi_histogram(
output_dir="/data/project/derivatives/ti-toolbox/analysis/sub-001",
whole_head_field_data=whole_head_values, # np.ndarray
roi_field_data=roi_values, # np.ndarray
whole_head_element_sizes=wh_sizes, # optional, np.ndarray
roi_element_sizes=roi_sizes, # optional, np.ndarray
filename="TI_max.nii.gz", # optional, used for title and output name
region_name="M1", # optional, ROI label
roi_field_value=0.152, # optional, draws vertical marker
data_type="element", # "element" or "voxel"
voxel_dims=(1.0, 1.0, 1.0), # optional, for voxel volume weighting
n_bins=100,
dpi=600,
)
Returns the path to the saved PDF, or None if input data is empty.
TI Metric Distributions¶
plot_montage_distributions¶
Creates three side-by-side histograms showing TImax, TImean, and Focality distributions across montages.
from tit.plotting import plot_montage_distributions
output_path = plot_montage_distributions(
timax_values=[0.21, 0.34, 0.18],
timean_values=[0.12, 0.19, 0.09],
focality_values=[0.85, 0.72, 0.91],
output_file="/data/output/montage_distributions.png",
dpi=300,
)
plot_intensity_vs_focality¶
Scatter plot of intensity versus focality, optionally colored by a composite index.
from tit.plotting import plot_intensity_vs_focality
output_path = plot_intensity_vs_focality(
intensity=[0.12, 0.19, 0.09, 0.25],
focality=[0.85, 0.72, 0.91, 0.68],
composite=[0.48, 0.55, 0.41, 0.60], # or None
output_file="/data/output/intensity_vs_focality.png",
dpi=300,
)
Statistical Plots¶
plot_permutation_null_distribution¶
Plots a permutation null distribution histogram with a significance threshold line and markers for observed clusters. Uses seaborn for styling.
from tit.plotting import plot_permutation_null_distribution
output_path = plot_permutation_null_distribution(
null_distribution=null_dist_array, # np.ndarray
threshold=42.0, # significance threshold
observed_clusters=[ # list of dicts
{"stat_value": 55.0, "p_value": 0.01},
{"stat_value": 30.0, "p_value": 0.12},
],
output_file="/data/output/null_distribution.pdf",
alpha=0.05,
cluster_stat="size", # "size" or "mass"
dpi=300,
)
plot_cluster_size_mass_correlation¶
Scatter plot with regression line showing the correlation between cluster size and cluster mass from permutation testing. Annotates Pearson r and p-value.
from tit.plotting import plot_cluster_size_mass_correlation
output_path = plot_cluster_size_mass_correlation(
cluster_sizes=sizes_array, # np.ndarray
cluster_masses=masses_array, # np.ndarray
output_file="/data/output/size_mass_correlation.pdf",
dpi=300,
)
Returns None if fewer than 2 non-zero data points are available.
Static Overlay Images¶
generate_static_overlay_images¶
Generates base64-encoded PNG slice images by overlaying a NIfTI field map on a T1 anatomical image. Produces 7 slices per orientation (axial, sagittal, coronal) with neurological convention labels.
from tit.plotting import generate_static_overlay_images
images = generate_static_overlay_images(
t1_file="/data/project/sub-001/anat/sub-001_T1w.nii.gz",
overlay_file="/data/project/derivatives/SimNIBS/sub-001/Simulations/TI_max.nii.gz",
subject_id="001", # optional
montage_name="motor", # optional
output_dir=None, # optional, not used for file output
)
# images is a dict with keys: "axial", "sagittal", "coronal"
# Each value is a list of dicts with: "base64", "slice_num", "overlay_voxels"
for entry in images["axial"]:
print(f"Slice {entry['slice_num']}: {entry['overlay_voxels']} overlay voxels")
Helpers¶
The tit.plotting._common module provides shared utilities used by all plotting functions.
SaveFigOptions¶
Frozen dataclass controlling figure save parameters.
from tit.plotting import SaveFigOptions
opts = SaveFigOptions(
dpi=600, # default: 600
bbox_inches="tight", # default: "tight"
facecolor="white", # default: "white"
edgecolor="none", # default: "none"
)
ensure_headless_matplotlib_backend¶
Sets the matplotlib backend to "Agg" (or a specified backend) for headless environments. Should be called before importing matplotlib.pyplot. No-ops if a backend is already active.
from tit.plotting import ensure_headless_matplotlib_backend
ensure_headless_matplotlib_backend() # defaults to "Agg"
ensure_headless_matplotlib_backend("Cairo") # or specify another backend
savefig_close¶
Saves a matplotlib Figure to disk and closes it. Uses fig.savefig (not plt.savefig) to avoid global pyplot state issues.
from tit.plotting import savefig_close, SaveFigOptions
path = savefig_close(
fig,
"/data/output/figure.pdf",
fmt="pdf", # optional explicit format
opts=SaveFigOptions(dpi=300), # optional overrides
)
Lazy Imports
The tit.plotting package uses lazy imports throughout. Importing tit.plotting does not pull in matplotlib, nibabel, seaborn, or scipy. These dependencies are only loaded when a plot function is actually called.
API Reference¶
Focality¶
tit.plotting.focality.plot_whole_head_roi_histogram ¶
plot_whole_head_roi_histogram(*, output_dir: str, whole_head_field_data: ndarray, roi_field_data: ndarray, whole_head_element_sizes: ndarray | None = None, roi_element_sizes: ndarray | None = None, filename: str | None = None, region_name: str | None = None, roi_field_value: float | None = None, data_type: str = 'element', voxel_dims: tuple | None = None, n_bins: int = 100, dpi: int = 600) -> str | None
Generate a whole-head histogram with ROI contribution color coding.
Efficient implementation: ROI contribution per bin is computed via vectorized division (no Python loops).
Source code in tit/plotting/focality.py
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 | |
TI Metrics¶
tit.plotting.ti_metrics.plot_montage_distributions ¶
plot_montage_distributions(*, timax_values: Sequence[float], timean_values: Sequence[float], focality_values: Sequence[float], output_file: str, dpi: int = 300) -> str | None
Create 3 side-by-side histograms for TImax, TImean and Focality distributions.
Source code in tit/plotting/ti_metrics.py
tit.plotting.ti_metrics.plot_intensity_vs_focality ¶
plot_intensity_vs_focality(*, intensity: Sequence[float], focality: Sequence[float], composite: Sequence[float] | None, output_file: str, dpi: int = 300) -> str | None
Scatter plot of intensity vs focality, optionally colored by composite index.
Source code in tit/plotting/ti_metrics.py
Statistical Plots¶
tit.plotting.stats.plot_permutation_null_distribution ¶
plot_permutation_null_distribution(null_distribution: ndarray, threshold: float, observed_clusters: Sequence[Mapping[str, float]], output_file: str, *, alpha: float = 0.05, cluster_stat: str = 'size', dpi: int = 300) -> str
Plot permutation null distribution with threshold and observed clusters.
Source code in tit/plotting/stats.py
tit.plotting.stats.plot_cluster_size_mass_correlation ¶
plot_cluster_size_mass_correlation(cluster_sizes: ndarray, cluster_masses: ndarray, output_file: str, *, dpi: int = 300) -> str | None
Plot correlation between cluster size and cluster mass from permutation null distribution.
Source code in tit/plotting/stats.py
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 | |
Static Overlays¶
tit.plotting.static_overlay.generate_static_overlay_images ¶
generate_static_overlay_images(*, t1_file: str, overlay_file: str, subject_id: str | None = None, montage_name: str | None = None, output_dir: str | None = None) -> dict[str, list[dict[str, Any]]]
Generate static overlay images for axial, sagittal, and coronal views.
'axial', 'sagittal', 'coronal'. Each value is a list of dicts:
- base64: base64-encoded PNG
- slice_num: 1-based slice index within that orientation
- overlay_voxels: number of non-zero overlay voxels in that slice
Source code in tit/plotting/static_overlay.py
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 | |
Common Utilities¶
tit.plotting._common.SaveFigOptions
dataclass
¶
SaveFigOptions(dpi: int = 600, bbox_inches: str = 'tight', facecolor: str = 'white', edgecolor: str = 'none')
tit.plotting._common.ensure_headless_matplotlib_backend ¶
ensure_headless_matplotlib_backend(backend: str = 'Agg') -> None
Best-effort backend setup for headless environments.
Important: - This should be called BEFORE importing matplotlib.pyplot. - If a backend is already active, we do not force-change it.
Source code in tit/plotting/_common.py
tit.plotting._common.savefig_close ¶
savefig_close(fig: Any, output_file: str, *, fmt: str | None = None, opts: SaveFigOptions = SaveFigOptions()) -> str
Save a matplotlib Figure and close it.
Uses fig.savefig (not plt.savefig) to avoid relying on global pyplot state.