### Setup example plot Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/walkthrough.html Imports necessary libraries, generates random tournament data, and initializes a matplotlib line plot. ```python 1import matplotlib.pyplot as plt 2import numpy as np 3import rijksplotlib as rpl 4 5 6def generate_random_game_score(number_of_games): 7 """Generate some random running totals.""" 8 return np.cumsum(np.random.randint(-1,2,number_of_games)) 9 10# Setup table soccer tournament 11np.random.seed(seed=43) 12number_of_games = 15 13roundnrs = np.arange(number_of_games) 14teams = [ 15 "data science", 16 "data engineering", 17 "dataviz", 18 "remote sensing", 19 "SRE", 20 "ontwikkelteam", 21] 22tournament_results = {team: generate_random_game_score(number_of_games) for team in teams} 23 24# Start plotting the scores 25fig, ax = plt.subplots() 26for team, score in tournament_results.items(): 27 plt.plot(roundnrs, score, label=team) ``` -------------------------------- ### Install documentation dependencies and build docs Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/installation.html Installs documentation-specific dependencies and generates HTML documentation. ```bash pip install ".[doc]" make --directory=doc html # if using Windows use .\doc\make.bat html ``` -------------------------------- ### Install rijksplotlib from source Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/installation.html Commands to clone the repository and install the package in editable mode. ```bash git clone https://gitlab.com/rwsdatalab/public/codebase/tools/rijksplotlib.git cd rijksplotlib pip install . ``` -------------------------------- ### Install development dependencies and run tests Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/installation.html Installs the package with development extras and executes the test suite. ```bash pip install ".[dev]" pytest ``` -------------------------------- ### Install development dependencies Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/contributing.html Install the package in editable mode along with all necessary development requirements. ```bash pip install -r requirements-dev.txt pip install . ``` -------------------------------- ### Install pre-commit hooks Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/contributing.html Initialize pre-commit hooks to ensure code quality standards are met before commits. ```bash pre-commit install ``` -------------------------------- ### Install rijksplotlib via pip Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/installation.html Standard installation command for the package. Requires Python 3.10 or higher. ```bash pip install rijksplotlib ``` -------------------------------- ### Create a styled histogram with rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/5ab63aac16eb09167d02dff644e58a11/plot_histogram_mpl.ipynb This example loads water data and generates a histogram with custom styling, titles, and RWS branding. ```python import os import sys import matplotlib.pyplot as plt import numpy as np import rijksplotlib as rpl import rijksplotlib.pyplot as rlt # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_waterinfo_data # noqa: E402 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns # Make figure _, ax = plt.subplots() # Make histogram with adjusted styling bins = np.arange(600, 1500, 20) plt.hist(x=df["hoogte"], bins=bins, edgecolor="white", alpha=0.75) # Make sure axes start and end at tick labels / grid lines plt.xlim([600, 1500]) plt.ylim([0, 400]) # Set titles and labels title = "Histogram van gemeten waterhoogten bij Lobith" subtitle = "Aantal dagelijkse gemiddelden van jan 2013 t/m aug 2023" rlt.title(title) rlt.subtitle(subtitle) rlt.xlabel("cm tov NAP") rlt.ylabel("") # Add source and logo components rlt.source("waterinfo.rws.nl (2023)") rlt.logo_rwsdatalab() rlt.show() ``` -------------------------------- ### Create a styled linechart with rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/38926cb4c0fdf47acc49e490afe4093a/plot_linechart_mpl.ipynb This example loads water data, processes it into a pivot table, and uses rijksplotlib helper functions to apply RWS styling, custom legends, and branding. ```python import os import sys import matplotlib.pyplot as plt import rijksplotlib as rpl import rijksplotlib.pyplot as rlt from rijksplotlib.color import rijkskleuren as rijkskleuren # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_waterinfo_data # noqa: E402 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns df["year"] = df.index.year df["dayofyear"] = df.index.dayofyear # df = df.reset_index() # Make figure _, ax = plt.subplots() # Prepare data df = df.pivot(columns="year", index="dayofyear", values="debiet") # Make background lines plt.plot(df, color=rijkskleuren["grijs-3"], linewidth=0.7) # Make foreground line of 2021 data plt.plot(df[2021], rijkskleuren["hemelblauw"]) # Customize plot ax.set_ylim([0, 8000]) ax.set_xlim([0, 366]) # Set titles and labels title = "De stortbui in de zomer van 2021 was een verrassing" subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" rlt.title(title) rlt.subtitle(subtitle) rlt.xlabel("dag van het jaar") rlt.ylabel("m3/s") # Make custom legend rlt.legend( handles=[ax.get_lines()[-1], ax.get_lines()[0]], labels=["2021", "2013 t/m 2023"], padding_right_inches=1.3, # Space needed for wider legend label ) # Add source and logo components rlt.source("waterinfo.rws.nl (2023)") rlt.logo_rwsdatalab() rlt.show() ``` -------------------------------- ### Create a styled line chart with Pandas and rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/34bdd8460bc0bccd76684251a771845f/plot_linechart_pd.ipynb This example shows how to pivot data, plot multiple lines with specific colors, and remove default Pandas styling to match RWS report standards. ```python import os import sys import matplotlib.pyplot as plt import rijksplotlib as rpl import rijksplotlib.pyplot as rlt from rijksplotlib.color import rijkskleuren # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_waterinfo_data # noqa: E402 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns df["year"] = df.index.year df["dayofyear"] = df.index.dayofyear df = df.reset_index() # Make figure _, ax = plt.subplots() df = df.pivot(columns="year", index="dayofyear", values="debiet") # Make background lines df.plot(ax=ax, color=rijkskleuren["grijs-3"], linewidth=0.7) # Make foreground line of 2021 data df[2021].plot(ax=ax, color=rijkskleuren["hemelblauw"]) # Remove redundant styling added by Pandas ax.set_title("") ax.xaxis.grid(visible=False) # Customize plot ax.set_ylim([0, 8000]) ax.set_xlim([0, 366]) # Set titles and labels title = "De stortbui in de zomer van 2021 was een verrassing" subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" rlt.title(title) rlt.subtitle(subtitle) rlt.xlabel("dag van het jaar") rlt.ylabel("m3/s") # Make custom legend rlt.legend( handles=[ax.get_lines()[-1], ax.get_lines()[0]], labels=["2021", "2013 t/m 2023"], padding_right_inches=1.3, # Space needed for wider legend label ) # Add source and logo components rlt.source("waterinfo.rws.nl (2023)") rlt.logo_rwsdatalab() rlt.show() ``` -------------------------------- ### Create a Seaborn Linechart with rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/802b9d50acd5f7cbfcd9a40b9dd5c7a5/plot_linechart_sns.ipynb This example loads water data, processes it by year and day, and uses Seaborn to plot multiple lines with custom RWS styling and branding. ```python import os import sys import matplotlib.pyplot as plt import seaborn as sns import rijksplotlib as rpl import rijksplotlib.pyplot as rlt from rijksplotlib.color import rijkskleuren # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_waterinfo_data # noqa: E402 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns df["year"] = df.index.year df["dayofyear"] = df.index.dayofyear df = df.reset_index() # Make figure _, ax = plt.subplots() # Make background lines sns.lineplot( df, x="dayofyear", y="debiet", hue="year", palette=[rijkskleuren["grijs-3"]], size="year", sizes=[0.7], legend="brief", ) # Make foreground line of 2021 data sns.lineplot( df[df.year == 2021], x="dayofyear", y="debiet", hue="year", palette=[rijkskleuren["hemelblauw"]], ) # Customize plot ax.set_ylim([0, 8000]) ax.set_xlim([0, 366]) # Set titles and labels title = "De stortbui in de zomer van 2021 was een verrassing" subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" rlt.title(title) rlt.subtitle(subtitle) rlt.xlabel("dag van het jaar") rlt.ylabel("m3/s") # Make custom legend rlt.legend( handles=[ax.get_lines()[-1], ax.get_lines()[0]], labels=["2021", "2013 t/m 2023"], padding_right_inches=1.3, # Space needed for wider legend label ) # Add source and logo components rlt.source("waterinfo.rws.nl (2023)") rlt.logo_rwsdatalab() rlt.show() ``` -------------------------------- ### Create a 2D filled overlay plot Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/ccbe0f9d917421c595b404781dfa219a/plot_filled_overlay.ipynb This script loads example data, processes overlapping regions into a categorical image, and renders the result with custom RWS styling and legends. ```python import os import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Patch import rijksplotlib as rpl import rijksplotlib.pyplot as rlt # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_overlay_data # noqa: E402 data = load_overlay_data() # Make figure with two subplots fig, axes = plt.subplots(ncols=2, figsize=(5.35, 2.8)) plt.subplots_adjust(wspace=0.125) # Show satellite figure in both subplots for ax in axes: ax.imshow(data["satfig"]) # Get cmap colors cmap = plt.get_cmap("rws:overlay-blauw") # make array with 0: no data, 1: registered data, # 2: where model and register overlap, and 3: only model image = np.zeros(data["modelfig"].shape) image[(data["modelfig"] - data["overlap"]) == 1] = 1 image[data["overlap"] == 1] = 2 image[(data["registerfig"] - data["overlap"]) == 1] = 3 # Show the modeled, overlapping and registered data plt.imshow(image, cmap=cmap, alpha=0.8) rlt.title("Beeldherkenningsmodel kan wegen nog niet goed onderscheiden") rlt.subtitle("Modelresultaten vergeleken met de Basisisregistratie Rijkswegen") for ax in axes: ax.xaxis.set_tick_params(labelbottom=False) ax.yaxis.set_tick_params(labelleft=False) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim([0, 800]) plt.axis("off") plt.subplots_adjust(bottom=0, left=0.03) legend_elements = [ Patch(facecolor=cmap.colors[1], label="model"), Patch(facecolor=cmap.colors[2], label="overlap"), Patch(facecolor=cmap.colors[3], label="basisregistratie"), ] rlt.legend(handles=legend_elements, padding_right_inches=1.2) rlt.source("Google Maps (2022) en RWS (2023)") rlt.logo_rwsdatalab(offset_y=10) rlt.show(disabled_errors=["xlabel", "ylabel"]) ``` -------------------------------- ### Validation log output Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/walkthrough.html Example of the log messages generated by the validation process when required figure elements are missing. ```text ERROR:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing a title, use rlt.title('your title') INFO:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing xlabel, is this correct? If not, use rlt.xlabel('your xlabel'). INFO:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing ylabel, is this correct? If not, use rlt.ylabel('your ylabel'). INFO:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing legend, is this correct? If not, use rlt.legend() WARNING:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing a source, use rlt.source('your source') WARNING:2023/08/31 10:27:14 AM - rijksplotlib.validate - Missing an RWS Datalab logo, use rlt.logo_rwsdatalab() or rlt.logo('My department name') ``` -------------------------------- ### Build documentation Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/contributing.html Generate the project documentation using Sphinx. ```bash make --directory=doc html # if using Windows use .\doc\make.bat html ``` -------------------------------- ### Get line height in points Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.utils.html Calculates the line height based on a matplotlib font scaling factor. ```python >>> get_lineheight_points("medium") 9.0 ``` -------------------------------- ### Adding x and y labels to a plot Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/functionalities/plot_3_x_and_ylabel.html Uses rlt.xlabel and rlt.ylabel to annotate axes after generating a base plot from a previous example. ```python 10 import matplotlib.pyplot as plt 11 import plot_2_subtitle 12 from matplotlib.axes import Axes 13 from matplotlib.figure import Figure 14 15 import rijksplotlib as rpl 16 import rijksplotlib.pyplot as rlt 17 18 19 def make_plot() -> tuple[Figure, Axes]: 20 """Add axis labels to the graph.""" 21 fig, ax = plot_2_subtitle.make_plot() 22 23 # Let's add the x and ylabel 24 rlt.xlabel("spelronde") 25 rlt.ylabel("score") 26 27 # Adjust the axis extents 28 plt.ylim([-8, 8]) 29 plt.xlim([0, 14]) 30 31 return fig, ax 32 33 34 if __name__ == "__main__": 35 make_plot() 36 37 doc = rpl.utils.resolve_path("doc") # Find doc folder 38 rlt.savefig( 39 doc / "_static/walkthrough_3_x_and_ylabel.png" 40 ) # Save image for doc/usage example ``` -------------------------------- ### Visualize all package colors Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/colors/plot_preview_color.html Orchestrates the plotting of tint, numbered, and individual colors into a structured figure layout. ```python 130 def plot_all_colors() -> None: 131 """Plot all colors.""" 132 tint_colors = [ 133 "lichtblauw", 134 "hemelblauw", 135 "donkerblauw", 136 "logoblauw", 137 "paars", 138 "violet", 139 "roze", 140 "robijnrood", 141 "rood", 142 "oranje", 143 "donkergeel", 144 "geel", 145 "donkerbruin", 146 "bruin", 147 "mosgroen", 148 "donkergroen", 149 "groen", 150 "mintgroen", 151 ] 152 numbered_colors = ["grijs"] 153 individual_colors = ["general"] 154 155 _check_all_colors_present(tint_colors + numbered_colors + individual_colors) 156 157 fig = plt.figure(figsize=(6.4, 10)) 158 subfigs = fig.subfigures(2, 1, height_ratios=[0.7, 0.3]) 159 160 # Add a plot for all rijkskleuren met 5 tinten 161 nrows = 3 162 figh = 10 163 ncols = 6 164 title = "Rijkskleuren en de 5 tinten" 165 plot_colors_in_subplot(tint_colors, title, nrows, ncols, figh, subfigs[0]) 166 subfigs[0].suptitle(title) 167 168 # Add a plot for all rijkskleuren met numbers 169 left_margin_ratio = 0.11 # Align the bottom figure patches with the top one 170 subfigs_bottom_ratio = (1 - left_margin_ratio) / 2 171 subfigs_bottom = subfigs[1].subfigures( 172 1, 173 3, 174 width_ratios=[left_margin_ratio, subfigs_bottom_ratio, subfigs_bottom_ratio], 175 ) 176 nrows = 1 177 ncols = 3 178 title = "Rijkskleuren met nummers" 179 plot_colors_in_subplot( 180 numbered_colors, title, nrows, ncols, figh, subfigs_bottom[1] 181 ) 182 183 # Add a plot for all remaining colors 184 title = "Algemene kleuren" 185 plot_colors_in_subplot( 186 individual_colors, title, nrows, ncols, figh, subfigs_bottom[2] 187 ) 188 subfigs[1].suptitle("Overige kleuren", y=1.1) 189 190 plt.show() 191 192 193 if __name__ == "__main__": 194 plot_all_colors() ``` -------------------------------- ### Run Pylint with rijksplotlib plugin Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/linter.html Execute Pylint on a specific file while loading the rijksplotlib plugin. ```bash pylint ./examples/histogram.py --load-plugins=rijksplotlib.pylint_rules ``` -------------------------------- ### Initialize and display figures with rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/getting_started.html Replace standard Matplotlib show and save calls with rlt equivalents to ensure RWS report compliance. ```python import rijksplotlib.pyplot as rlt # plot your graph here # rlt.show() # or # rlt.savefig() ``` -------------------------------- ### Add a subtitle to a plot Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/0f7b36fac1bc12044959c2a1892e7093/plot_2_subtitle.ipynb Uses the rlt.subtitle function to append a subtitle to an existing figure. The example assumes a base plot is created via plot_1_title and saves the result to a specified directory. ```python import plot_1_title from matplotlib.axes import Axes from matplotlib.figure import Figure import rijksplotlib as rpl import rijksplotlib.pyplot as rlt def make_plot() -> tuple[Figure, Axes]: """Add a subtitle to the graph.""" fig, ax = plot_1_title.make_plot() # Let's add the subtitle rlt.subtitle("Teamscores per spelronde van het RWS Datalab Tafelvoetbaltoernooi") return fig, ax if __name__ == "__main__": make_plot() doc = rpl.utils.resolve_path("doc") # Find doc folder rlt.savefig( doc / "_static/walkthrough_2_subtitle.png" ) # Save image for doc/usage example ``` -------------------------------- ### Main execution block Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/matplotlib/plot_effect_of_package.html Main script execution that resolves paths, generates figures, and saves them as images. ```python if __name__ == "__main__": # Add the save location doc = rpl.utils.resolve_path("doc") # Find doc folder examples = rpl.utils.resolve_path("examples") fig = make_default_matplotlib_figure() img_matplotlib = put_figure_on_empty_page(fig) save_image(img_matplotlib, doc / "static/images/startpagina_1_matplotlib.png", 0.5) import rijksplotlib as rpl # noqa: E402 # Normally not necessary: Undo mpl.rcParamsDefault rpl.stylesheets.apply_stylesheet() fig = make_figure_with_full_rijksplotlib_functionality() img_full_rws = put_figure_on_empty_page(fig) save_image( img_full_rws, doc / "static/images/startpagina_3_import_rijksplotlib_and_use_helper_functions.png", 0.5, ) ``` -------------------------------- ### Retrieve text and color Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.utils.html Parses a string for color formatting tags in the format . ```python >>> get_text_color("", "black") ("some text", "red") ``` -------------------------------- ### rijksplotlib.create_logger() Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.html Creates and configures a logger for the package using the logginginitializer package, logging to the console at INFO level or higher. ```APIDOC ## rijksplotlib.create_logger() ### Description Creates a logger for the package. The logger is configured using the LoggingConfig class from the logginginitializer package and is set to log to the console with level INFO or higher. ### Returns - **None** ``` -------------------------------- ### Create a styled Seaborn linechart Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/linecharts/plot_linechart_sns.html This script loads water data, creates a multi-line plot with background and foreground series, and applies RWS-specific styling. ```python 17 import os 18 import sys 19 20 import matplotlib.pyplot as plt 21 import seaborn as sns 22 23 import rijksplotlib as rpl 24 import rijksplotlib.pyplot as rlt 25 from rijksplotlib.color import rijkskleuren 26 27 # Load data 28 if __name__ == "__main__": 29 examples = rpl.utils.resolve_path("examples") 30 sys.path.append(os.path.abspath(examples)) 31 32 from data.load_example_data import load_waterinfo_data # noqa: E402 33 34 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns 35 df["year"] = df.index.year 36 df["dayofyear"] = df.index.dayofyear 37 df = df.reset_index() 38 39 # Make figure 40 _, ax = plt.subplots() 41 42 # Make background lines 43 sns.lineplot( 44 df, 45 x="dayofyear", 46 y="debiet", 47 hue="year", 48 palette=[rijkskleuren["grijs-3"]], 49 size="year", 50 sizes=[0.7], 51 legend="brief", 52 ) 53 # Make foreground line of 2021 data 54 sns.lineplot( 55 df[df.year == 2021], 56 x="dayofyear", 57 y="debiet", 58 hue="year", 59 palette=[rijkskleuren["hemelblauw"]], 60 ) 61 62 # Customize plot 63 ax.set_ylim([0, 8000]) 64 ax.set_xlim([0, 366]) 65 66 # Set titles and labels 67 title = "De stortbui in de zomer van 2021 was een verrassing" 68 subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" 69 70 rlt.title(title) 71 rlt.subtitle(subtitle) 72 rlt.xlabel("dag van het jaar") 73 rlt.ylabel("m3/s") 74 75 # Make custom legend 76 rlt.legend( 77 handles=[ax.get_lines()[-1], ax.get_lines()[0]], 78 labels=["2021", "2013 t/m 2023"], 79 padding_right_inches=1.3, # Space needed for wider legend label 80 ) 81 82 # Add source and logo components 83 rlt.source("waterinfo.rws.nl (2023)") 84 rlt.logo_rwsdatalab() 85 86 rlt.show() ``` -------------------------------- ### Create a bar chart with custom colors and labels Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/4bccfc9a14ae9cc03a6964605efd4c51/plot_bar_color_demo.ipynb Uses rijksplotlib colors and styling to generate a bar chart with specific labels and legend formatting. ```python import matplotlib.pyplot as plt import rijksplotlib.pyplot as rlt from rijksplotlib.color import rijkskleuren fig, ax = plt.subplots() fruits = ["apple", "blueberry", "cherry", "orange"] counts = [40, 100, 30, 55] bar_labels = ["red", "blue", "_red", "orange"] bar_colors = [ rijkskleuren["robijnrood"], rijkskleuren["hemelblauw"], rijkskleuren["robijnrood"], rijkskleuren["oranje"], ] ax.bar(fruits, counts, label=bar_labels, color=bar_colors) rlt.ylabel("fruit supply") rlt.title("Fruit supply by kind and color") rlt.legend(title="Fruit color", padding_right_inches=1) rlt.source( "https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_colors.html" ) rlt.logo_rwsdatalab() rlt.show() ``` -------------------------------- ### Create a styled linechart with Matplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/linecharts/plot_linechart_mpl.html Uses rijksplotlib to format a linechart with specific RWS colors, titles, and branding elements. ```python 11 import os 12 import sys 13 14 import matplotlib.pyplot as plt 15 16 import rijksplotlib as rpl 17 import rijksplotlib.pyplot as rlt 18 from rijksplotlib.color import rijkskleuren as rijkskleuren 19 20 # Load data 21 if __name__ == "__main__": 22 examples = rpl.utils.resolve_path("examples") 23 sys.path.append(os.path.abspath(examples)) 24 25 from data.load_example_data import load_waterinfo_data # noqa: E402 26 27 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns 28 df["year"] = df.index.year 29 df["dayofyear"] = df.index.dayofyear 30 # df = df.reset_index() 31 32 # Make figure 33 _, ax = plt.subplots() 34 35 # Prepare data 36 df = df.pivot(columns="year", index="dayofyear", values="debiet") 37 38 # Make background lines 39 plt.plot(df, color=rijkskleuren["grijs-3"], linewidth=0.7) 40 # Make foreground line of 2021 data 41 plt.plot(df[2021], rijkskleuren["hemelblauw"]) 42 43 # Customize plot 44 ax.set_ylim([0, 8000]) 45 ax.set_xlim([0, 366]) 46 47 # Set titles and labels 48 title = "De stortbui in de zomer van 2021 was een verrassing" 49 subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" 50 51 rlt.title(title) 52 rlt.subtitle(subtitle) 53 rlt.xlabel("dag van het jaar") 54 rlt.ylabel("m3/s") 55 56 # Make custom legend 57 rlt.legend( 58 handles=[ax.get_lines()[-1], ax.get_lines()[0]], 59 labels=["2021", "2013 t/m 2023"], 60 padding_right_inches=1.3, # Space needed for wider legend label 61 ) 62 63 # Add source and logo components 64 rlt.source("waterinfo.rws.nl (2023)") 65 rlt.logo_rwsdatalab() 66 67 rlt.show() ``` -------------------------------- ### Importing rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.html Recommended import style for using rijksplotlib alongside matplotlib. ```python import rijksplotlib as rpl import matplotlib as mpl import matplotlib.pyplot as plt import rijksplotlib.pyplot as rlt ``` -------------------------------- ### Configure GitLab CI for Pylint Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/installation.html Template for integrating rijksplotlib Pylint rules into a GitLab CI pipeline. ```yaml # Rest of your yaml pylint: stage: static analysis extends: .template_runtime rules: - if: $CI_COMMIT_BRANCH script: - pylint --exit-zero --output-format=text MY_PACKAGE_NAME --load-plugins=rijksplotlib.pylint_rules | tee pylint.log - PYLINT_SCORE=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.log) - *create_pylint_badge - cat pylint.log - echo "pylint score is $PYLINT_SCORE" artifacts: paths: - pylint.svg ``` -------------------------------- ### Create a listed colormap from a string Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.colormaps.html Generates a ListedColormap from a space-separated string of color names. The resulting colormap name is automatically prefixed with 'rws:'. ```python >>> cmap = cmap_from_string("hemelblauw grijs-2", name="blauw-grijs") >>> cmap.name 'rws:blauw-grijs' ``` -------------------------------- ### Utility Functions Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.utils.html A collection of helper functions for plot configuration and data processing. ```APIDOC ## Utility Functions ### Functions - `get_bottom_margin()`: Retrieves the current bottom margin setting. - `get_fontsize_points()`: Retrieves the current font size in points. - `get_lineheight_points()`: Retrieves the current line height in points. - `get_right_margin()`: Retrieves the current right margin setting. - `get_text_color()`: Retrieves the current text color configuration. - `get_top_margin()`: Retrieves the current top margin setting. - `inches_to_points(inches)`: Converts a value from inches to points. - `increase_bottom_margin(value)`: Increases the bottom margin by a specified value. - `increase_right_margin(value)`: Increases the right margin by a specified value. - `increase_top_margin(value)`: Increases the top margin by a specified value. - `points_to_inches(points)`: Converts a value from points to inches. - `resolve_path(path)`: Resolves a given file path. - `split_between_brackets(text)`: Splits a string into a list of strings based on '<' and '>' delimiters. ``` -------------------------------- ### Create a styled linechart with Pandas Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/auto_examples/linecharts/plot_linechart_pd.html Uses rijksplotlib to style a Pandas-generated linechart, including custom titles, labels, and RWS branding. ```python 15 import os 16 import sys 17 18 import matplotlib.pyplot as plt 19 20 import rijksplotlib as rpl 21 import rijksplotlib.pyplot as rlt 22 from rijksplotlib.color import rijkskleuren 23 24 # Load data 25 if __name__ == "__main__": 26 examples = rpl.utils.resolve_path("examples") 27 sys.path.append(os.path.abspath(examples)) 28 29 from data.load_example_data import load_waterinfo_data # noqa: E402 30 31 df = load_waterinfo_data() # pd.DataFrame with date, hoogte and debiet columns 32 df["year"] = df.index.year 33 df["dayofyear"] = df.index.dayofyear 34 df = df.reset_index() 35 36 # Make figure 37 _, ax = plt.subplots() 38 39 df = df.pivot(columns="year", index="dayofyear", values="debiet") 40 41 # Make background lines 42 df.plot(ax=ax, color=rijkskleuren["grijs-3"], linewidth=0.7) 43 # Make foreground line of 2021 data 44 df[2021].plot(ax=ax, color=rijkskleuren["hemelblauw"]) 45 # Remove redundant styling added by Pandas 46 ax.set_title("") 47 ax.xaxis.grid(visible=False) 48 49 # Customize plot 50 ax.set_ylim([0, 8000]) 51 ax.set_xlim([0, 366]) 52 53 # Set titles and labels 54 title = "De stortbui in de zomer van 2021 was een verrassing" 55 subtitle = "Dagelijks gemiddelde debiet van de Waal bij Lobith" 56 57 rlt.title(title) 58 rlt.subtitle(subtitle) 59 rlt.xlabel("dag van het jaar") 60 rlt.ylabel("m3/s") 61 62 # Make custom legend 63 rlt.legend( 64 handles=[ax.get_lines()[-1], ax.get_lines()[0]], 65 labels=["2021", "2013 t/m 2023"], 66 padding_right_inches=1.3, # Space needed for wider legend label 67 ) 68 69 # Add source and logo components 70 rlt.source("waterinfo.rws.nl (2023)") 71 rlt.logo_rwsdatalab() 72 73 rlt.show() ``` -------------------------------- ### Create a hatched overlay plot Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/f223ca058e118647f708b4b5851ce2de/plot_hatched_overlay.ipynb Uses matplotlib and rijksplotlib to overlay model and registration data on a satellite image, utilizing contourf for hatching and custom legend elements. ```python import os import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Patch import rijksplotlib as rpl import rijksplotlib.pyplot as rlt from rijksplotlib.color import rijkskleuren # Load data if __name__ == "__main__": examples = rpl.utils.resolve_path("examples") sys.path.append(os.path.abspath(examples)) from data.load_example_data import load_overlay_data # noqa: E402 data = load_overlay_data() # Make figure with two subplots fig, axes = plt.subplots(ncols=2) plt.subplots_adjust(wspace=0.125) # Show satellite figure in both subplots for ax in axes: ax.imshow(data["satfig"]) # Set colors model_color = rijkskleuren["hemelblauw"] register_color = rijkskleuren["grijs-4"] # make array with 0: no data, 1: registered data, # 2: where model and register overlap, and 3: only model image = np.zeros(data["modelfig"].shape) image[(data["modelfig"] - data["overlap"]) == 1] = 1 image[data["overlap"] == 1] = 2 image[(data["registerfig"] - data["overlap"]) == 1] = 3 # make contourfill plot OV = axes[1].contourf( image, levels=np.arange(-0.5, 4, 1), colors=["white", model_color, model_color, register_color], alpha=0.8, hatches=["", "", "////", ""], ) # Remove the edges around the contourf zones for collection in OV.collections: collection.set_edgecolor(register_color) collection.set_linewidth(0.0) rlt.title("Beeldherkenningsmodel kan wegen nog niet goed onderscheiden") rlt.subtitle("Modelresultaten vergeleken met de Basisisregistratie Rijkswegen") for ax in axes: ax.xaxis.set_tick_params(labelbottom=False) ax.yaxis.set_tick_params(labelleft=False) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim([0, 800]) plt.axis("off") plt.subplots_adjust(bottom=0, left=0.03) legend_elements = [ Patch(facecolor=model_color, label="model"), Patch( facecolor=model_color, hatch="////", edgecolor=register_color, label="overlap" ), Patch(facecolor=register_color, label="basisregistratie"), ] rlt.legend(handles=legend_elements, padding_right_inches=1.2) rlt.source("Google Maps (2022) en RWS (2023)") rlt.logo_rwsdatalab(offset_y=22) rlt.show(disabled_errors=["xlabel", "ylabel"]) ``` -------------------------------- ### Add a figure subtitle Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/walkthrough.html Use rlt.subtitle() to provide additional descriptive context, which is recommended when the main title is a takeaway statement. ```python rlt.subtitle("Teamscores per spelronde van het RWS Datalab Tafelvoetbaltoernooi") ``` -------------------------------- ### Visualize and validate color swatches with matplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/3d5f6f1d0e42a181bf5edb3510a450c6/plot_preview_color.ipynb Contains helper functions to check color completeness, manage subplot axes, and render color rectangles for the rijksplotlib library. ```python from typing import Optional import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.figure import Figure import rijksplotlib as rpl def _check_all_colors_present(colors_to_check: list[str]) -> None: """Check if the list of colors is still complete.""" all_colors = dir(rpl.color) all_colors = [c for c in all_colors if c[0] != "_"] neglect_attributes = ["rijkskleuren"] all_colors = [c for c in all_colors if c not in neglect_attributes] for color in all_colors: if color not in colors_to_check: raise Exception( "The color list is not complete!" f"Missing color '{color}' which is in rpl.color, " "but not in the list to be shown." ) def _disable_x_and_y_axis_for_ax( axs: plt.Axes, start_index: int, nrows: int, ncols: int ) -> None: """Disable the lines and labels of an axis.""" for i in range(start_index, nrows * ncols): ax, _ = _get_ith_ax(axs, i, ncols) ax.axis("off") def _get_ith_ax(axs: plt.Axes, i: int, ncols: int) -> tuple[plt.Axes, int]: """Return the ith axis.""" if axs.ndim == 1: ax = axs[i] colnr = i else: rownr = i // ncols colnr = i % ncols ax = axs[rownr, colnr] return (ax, colnr) def plot_color(color_name: str, ax: plt.Axes, show_yaxis: bool = False) -> None: """Plot the color by adding a color rect for each tint in the color.""" color_dict = getattr(rpl.color, color_name) ncolors = len(color_dict) yticks_pos = [] color_names = [] for colornr, color in enumerate(sorted(color_dict.keys())): padding = 0.02 color_patch_height = 1 / ncolors - padding rect = mpl.patches.Rectangle( # type: ignore[attr-defined] (0, 1 - (colornr + 1) * (color_patch_height + padding)), 1, color_patch_height, color=color_dict[color], edgecolor="none", ) ax.add_patch(rect) ax.set_title(color_name, fontsize=9, fontweight="light") # Plot the hex colors # ax.text( # x=0.01, # y=1 - colornr / ncolors - 0.5 / ncolors, # s=color_dict[color], # fontsize=7, # va="center" # ) yticks_pos.append(1 - colornr / ncolors - 0.5 / ncolors) color_names.append(color) if show_yaxis: ax.set_yticks(yticks_pos) ax.set_yticklabels(color_names) ax.tick_params( axis="both", which="both", length=0 ) # Hide tickmarks (set length of mark to 0) ax.get_xaxis().set_visible(False) ax.spines[["bottom"]].set_visible(False) ax.grid(visible=False) else: ax.axis("off") def plot_colors_in_subplot( colors: list[str], title: str, nrows: int, ncols: int, figh: float, subfig: Optional[Figure] = None, ) -> None: """Plot a list of colors as known by the rpl package.""" if subfig: axs = subfig.subplots(nrows, ncols) else: _, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(6.4, figh)) plt.subplots_adjust(wspace=0.8, top=0.9, left=0.2) # Put each color in its own plot for i, color_dict_name in enumerate(colors): ax, colnr = _get_ith_ax(axs, i, ncols) plot_color(color_dict_name, ax, colnr == 0) _disable_x_and_y_axis_for_ax(axs, len(colors), nrows, ncols) if subfig: return # Add extra elements and show plt.suptitle(title) plt.show() def plot_all_colors() -> None: """Plot all colors.""" tint_colors = [ "lichtblauw", "hemelblauw", "donkerblauw", "logoblauw", "paars", "violet", "roze", "robijnrood", "rood", "oranje", "donkergeel", "geel", "donkerbruin", "bruin", "mosgroen", "donkergroen", "groen", "mintgroen", ] numbered_colors = ["grijs"] individual_colors = ["general"] _check_all_colors_present(tint_colors + numbered_colors + individual_colors) fig = plt.figure(figsize=(6.4, 10)) subfigs = fig.subfigures(2, 1, height_ratios=[0.7, 0.3]) # Add a plot for all rijkskleuren met 5 tinten nrows = 3 figh = 10 ncols ``` -------------------------------- ### Save and Show Figures with rijksplotlib Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/61b631cef0774bac81e0fdbd9290708a/plot_0_show_and_savefig.ipynb Uses rlt.savefig and rlt.show to output plots while triggering automated validation logging. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.axes import Axes from matplotlib.figure import Figure import rijksplotlib as rpl import rijksplotlib.pyplot as rlt def example_setup() -> tuple[Figure, Axes]: """Generate the example lineplot with random data: a fantasy table soccer league.""" def generate_random_game_score(number_of_games): """Generate some random running totals.""" return np.cumsum(np.random.randint(-1, 2, number_of_games)) # Setup table soccer tournament # Make the data np.random.seed(seed=43) number_of_games = 15 roundnrs = np.arange(number_of_games) teams = [ "data science", "data engineering", "dataviz", "remote sensing", "SRE", "ontwikkelteam", ] tournament_results = { team: generate_random_game_score(number_of_games) for team in teams } # Start plotting the scores fig, ax = plt.subplots() for team, score in tournament_results.items(): plt.plot(roundnrs, score, label=team) return fig, ax if __name__ == "__main__": example_setup() # Instead of using plt.savefig() or plt.show() # use rlt.savefig() and rlt.show(). # This will output logging with how to improve your graph. doc = rpl.utils.resolve_path("doc") # Find doc folder rlt.savefig(doc / "_static/walkthrough_0_savefig.png") # Or if you just want to see the plot: # rlt.show() ``` -------------------------------- ### Create a feature or bug fix branch Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/contributing.html Commands to create a new branch based on the develop branch for general contributions. ```bash git fetch origin git checkout -b your-branch-name origin/develop ``` -------------------------------- ### rijksplotlib.utils.resolve_path Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/apidocs/rijksplotlib.utils.html Resolves a path relative to the root project directory. ```APIDOC ## rijksplotlib.utils.resolve_path(path='') ### Description Resolve a path relative to the root project directory. Note: This function only works if the repository structure is maintained. ### Parameters - **path** (str) - Optional - The subpath to resolve, leave empty to get the root project directory. ### Response - **Return** (Path) - An absolute path to the subpath. ``` -------------------------------- ### Visualize RWS Colormaps Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/_downloads/b13760ff9757095c143c41741bcd80a3/plot_preview_colormaps.ipynb Generates a figure with subplots for each colormap category to preview available gradients. ```python other_cmaps}, ] # Make the figure fig = plt.figure(figsize=(6.4, 10)) # Add +1 and +5 to account for a title per category color gradient adjust_for_title_ratio = 0.01 subfigs = fig.subfigures( 5, 1, height_ratios=[ (len(cmap["cmap_names"]) + adjust_for_title_ratio) / nrcmaps + 5 * adjust_for_title_ratio for cmap in cmaps ], ) for i, cmap in enumerate(cmaps): if len(cmap["cmap_names"]): plot_color_gradients( cmap["title"], cmap["cmap_names"], subfigs[i] # type: ignore[arg-type] ) plt.show() if __name__ == "__main__": plot_rws_colormaps() ``` -------------------------------- ### Create a critical bug fix branch Source: https://rwsdatalab.gitlab.io/public/codebase/tools/rijksplotlib/contributing.html Commands to create a new branch based on the main branch for critical fixes. ```bash git fetch origin git checkout -b your-branch-name origin/main ```