|
| 1 | +""" pyplots.ai |
| 2 | +contour-map-geographic: Contour Lines on Geographic Map |
| 3 | +Library: altair 6.0.0 | Python 3.13.11 |
| 4 | +Quality: 82/100 | Created: 2026-01-17 |
| 5 | +""" |
| 6 | + |
| 7 | +import altair as alt |
| 8 | +import numpy as np |
| 9 | +import pandas as pd |
| 10 | + |
| 11 | + |
| 12 | +# Data - Generate temperature-like data for Europe region |
| 13 | +np.random.seed(42) |
| 14 | + |
| 15 | +# Create dense grid covering wider Europe region to fill map canvas |
| 16 | +lon_range = np.linspace(-25, 55, 140) |
| 17 | +lat_range = np.linspace(30, 72, 90) |
| 18 | +lon_grid, lat_grid = np.meshgrid(lon_range, lat_range) |
| 19 | + |
| 20 | +# Generate temperature pattern (decreases with latitude, varies with longitude) |
| 21 | +temperature = ( |
| 22 | + 30 |
| 23 | + - 0.6 * (lat_grid - 30) # Cooler as you go north |
| 24 | + + 3 * np.sin((lon_grid + 10) / 15) # East-west variation (Gulf Stream effect) |
| 25 | + + 2 * np.cos(lat_grid / 10) # Additional pattern |
| 26 | + - 5 * np.exp(-((lat_grid - 47) ** 2 + (lon_grid - 10) ** 2) / 100) # Alps cold spot |
| 27 | + - 3 * np.exp(-((lat_grid - 65) ** 2 + (lon_grid - 25) ** 2) / 150) # Scandinavian cold |
| 28 | + + np.random.normal(0, 0.3, lon_grid.shape) # Minimal noise for smoother contours |
| 29 | +) |
| 30 | + |
| 31 | +# Clip to realistic range |
| 32 | +temperature = np.clip(temperature, -15, 35) |
| 33 | + |
| 34 | +# Create DataFrame |
| 35 | +df = pd.DataFrame( |
| 36 | + {"longitude": lon_grid.flatten(), "latitude": lat_grid.flatten(), "temperature": temperature.flatten()} |
| 37 | +) |
| 38 | + |
| 39 | +# Define contour levels for labeling |
| 40 | +contour_levels = [-10, -5, 0, 5, 10, 15, 20, 25, 30] |
| 41 | + |
| 42 | +# Load world countries for geographic context |
| 43 | +countries = alt.topo_feature("https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json", "countries") |
| 44 | + |
| 45 | +# Map projection settings - centered on Europe with better coverage |
| 46 | +projection_params = {"type": "mercator", "scale": 550, "center": [15, 52]} |
| 47 | + |
| 48 | +# Base map - world countries with subtle styling |
| 49 | +base = ( |
| 50 | + alt.Chart(countries) |
| 51 | + .mark_geoshape(fill="#E8E8E8", stroke="#AAAAAA", strokeWidth=0.5) |
| 52 | + .project(**projection_params) |
| 53 | + .properties(width=1600, height=900) |
| 54 | +) |
| 55 | + |
| 56 | +# Create smooth filled contour visualization using mark_square for cleaner coverage |
| 57 | +filled_contours = ( |
| 58 | + alt.Chart(df) |
| 59 | + .mark_square(size=200, opacity=0.92) |
| 60 | + .encode( |
| 61 | + longitude="longitude:Q", |
| 62 | + latitude="latitude:Q", |
| 63 | + color=alt.Color( |
| 64 | + "temperature:Q", |
| 65 | + scale=alt.Scale(scheme="redyellowblue", reverse=True, domain=[-10, 30]), |
| 66 | + legend=alt.Legend( |
| 67 | + title="Temperature (°C)", |
| 68 | + titleFontSize=20, |
| 69 | + labelFontSize=16, |
| 70 | + gradientLength=450, |
| 71 | + gradientThickness=30, |
| 72 | + orient="right", |
| 73 | + offset=20, |
| 74 | + ), |
| 75 | + ), |
| 76 | + tooltip=[ |
| 77 | + alt.Tooltip("longitude:Q", format=".1f", title="Longitude"), |
| 78 | + alt.Tooltip("latitude:Q", format=".1f", title="Latitude"), |
| 79 | + alt.Tooltip("temperature:Q", format=".1f", title="Temperature (°C)"), |
| 80 | + ], |
| 81 | + ) |
| 82 | + .project(**projection_params) |
| 83 | + .properties(width=1600, height=900) |
| 84 | +) |
| 85 | + |
| 86 | +# Create contour line data by identifying boundary points between temperature bins |
| 87 | +# Use tighter threshold for cleaner isolines |
| 88 | +contour_data = [] |
| 89 | +for level in contour_levels[1:-1]: # Skip extreme ends |
| 90 | + mask = np.abs(df["temperature"] - level) < 0.5 |
| 91 | + level_points = df[mask].copy() |
| 92 | + level_points["contour_value"] = level |
| 93 | + level_points["contour_label"] = f"{level}°C" |
| 94 | + contour_data.append(level_points) |
| 95 | + |
| 96 | +contour_df = pd.concat(contour_data, ignore_index=True) |
| 97 | + |
| 98 | +# Contour lines layer - more prominent strokes forming isolines |
| 99 | +contour_lines = ( |
| 100 | + alt.Chart(contour_df) |
| 101 | + .mark_circle(size=25, opacity=0.85) |
| 102 | + .encode(longitude="longitude:Q", latitude="latitude:Q", color=alt.value("#1a1a1a")) |
| 103 | + .project(**projection_params) |
| 104 | + .properties(width=1600, height=900) |
| 105 | +) |
| 106 | + |
| 107 | +# Create contour labels at strategic positions |
| 108 | +# Sample representative points along each contour level for labeling |
| 109 | +label_data = [] |
| 110 | +for level in [0, 10, 20]: |
| 111 | + level_points = contour_df[contour_df["contour_value"] == level] |
| 112 | + if len(level_points) > 0: |
| 113 | + # Select points at different longitudes for label placement |
| 114 | + for target_lon in [-10, 10, 30]: |
| 115 | + closest_idx = (level_points["longitude"] - target_lon).abs().idxmin() |
| 116 | + point = level_points.loc[closest_idx].copy() |
| 117 | + label_data.append({"longitude": point["longitude"], "latitude": point["latitude"], "label": f"{level}°C"}) |
| 118 | + |
| 119 | +label_df = pd.DataFrame(label_data) |
| 120 | + |
| 121 | +# Contour value labels with higher contrast |
| 122 | +contour_labels = ( |
| 123 | + alt.Chart(label_df) |
| 124 | + .mark_text(fontSize=18, fontWeight="bold", fill="#000000", stroke="#FFFFFF", strokeWidth=3) |
| 125 | + .encode(longitude="longitude:Q", latitude="latitude:Q", text="label:N") |
| 126 | + .project(**projection_params) |
| 127 | + .properties(width=1600, height=900) |
| 128 | +) |
| 129 | + |
| 130 | +# Create latitude/longitude axis labels for map edges |
| 131 | +# Longitude labels along bottom |
| 132 | +lon_labels_data = pd.DataFrame({"longitude": [-20, -10, 0, 10, 20, 30, 40, 50], "latitude": [31] * 8}) |
| 133 | +lon_labels_data["label"] = lon_labels_data["longitude"].apply( |
| 134 | + lambda x: f"{abs(x)}°{'W' if x < 0 else 'E'}" if x != 0 else "0°" |
| 135 | +) |
| 136 | + |
| 137 | +lon_axis_labels = ( |
| 138 | + alt.Chart(lon_labels_data) |
| 139 | + .mark_text(fontSize=14, fontWeight="normal", fill="#333333", dy=12) |
| 140 | + .encode(longitude="longitude:Q", latitude="latitude:Q", text="label:N") |
| 141 | + .project(**projection_params) |
| 142 | + .properties(width=1600, height=900) |
| 143 | +) |
| 144 | + |
| 145 | +# Latitude labels along left edge |
| 146 | +lat_labels_data = pd.DataFrame({"longitude": [-24] * 5, "latitude": [35, 45, 55, 65, 70]}) |
| 147 | +lat_labels_data["label"] = lat_labels_data["latitude"].apply(lambda x: f"{x}°N") |
| 148 | + |
| 149 | +lat_axis_labels = ( |
| 150 | + alt.Chart(lat_labels_data) |
| 151 | + .mark_text(fontSize=14, fontWeight="normal", fill="#333333", dx=-12, align="right") |
| 152 | + .encode(longitude="longitude:Q", latitude="latitude:Q", text="label:N") |
| 153 | + .project(**projection_params) |
| 154 | + .properties(width=1600, height=900) |
| 155 | +) |
| 156 | + |
| 157 | +# Layer all components: base map, filled contours, contour lines, labels, axis labels |
| 158 | +chart = ( |
| 159 | + alt.layer(base, filled_contours, contour_lines, contour_labels, lon_axis_labels, lat_axis_labels) |
| 160 | + .properties( |
| 161 | + width=1600, |
| 162 | + height=900, |
| 163 | + title=alt.Title("contour-map-geographic · altair · pyplots.ai", fontSize=28, anchor="middle", color="#333333"), |
| 164 | + ) |
| 165 | + .configure_view(strokeWidth=0) |
| 166 | +) |
| 167 | + |
| 168 | +# Save outputs |
| 169 | +chart.save("plot.png", scale_factor=3.0) |
| 170 | +chart.save("plot.html") |
0 commit comments