### Test HoloViz Package Installations Source: https://holoviz.org/tutorial/Setup Imports several HoloViz libraries (datashader, panel, hvplot, param, holoviews) and uses a helper function 'check_packages' to verify their correct installation. It also sets up HoloViews extensions for Bokeh and Matplotlib. ```python import datashader, panel, hvplot, param, holoviews as hv # noqa from package_checker import check_packages hv.extension('bokeh', 'matplotlib') packages = ['datashader', 'holoviews', 'panel', 'hvplot', 'param'] check_packages(packages) ``` -------------------------------- ### Perform editable install with dependencies Source: https://holoviz.org/contribute Installs the project in editable mode, including specified optional dependencies like 'tests' and 'examples'. This allows for direct code changes to be reflected without reinstallation. Multiple channels can be specified for package sources. ```shell doit develop_install -c channel1 -c channel2 -o tests -o ... -o ... ``` ```shell doit develop_install -c pyviz/label/dev -c conda-forge -o tests -o examples ``` -------------------------------- ### Launch Jupyter Lab with Anaconda Project Source: https://holoviz.org/tutorial/Setup Launches the Jupyter Lab interface using anaconda-project. This command will download necessary packages, set up a dedicated conda environment for the tutorial, and then start Jupyter Lab. ```bash anaconda-project run jupyter lab ``` -------------------------------- ### Create and Activate Conda Environment for Anaconda Project Source: https://holoviz.org/tutorial/Setup Creates a new conda environment named 'project' and installs the 'anaconda-project' package, which is used to manage tutorial dependencies. This ensures a clean and isolated environment for the tutorial. ```bash conda create -n project "anaconda-project>=0.11" conda activate project ``` -------------------------------- ### Run examples tests Source: https://holoviz.org/contribute Executes tests related to the project's examples, often involving notebooks. This is used to verify that example code functions correctly. ```shell doit test_examples. ``` -------------------------------- ### Download and Unzip Tutorial Project Files (macOS/Linux) Source: https://holoviz.org/tutorial/Setup Downloads the HoloViz tutorial ZIP archive using curl and unzips it into a 'holoviz_tutorial' directory. It then navigates into the extracted directory. This is specific to macOS and Linux environments. ```bash curl -o holoviz_tutorial.zip "https://assets.holoviz.org/holoviz/tutorial/holoviz_tutorial.zip" unzip holoviz_tutorial.zip -d holoviz_tutorial cd holoviz_tutorial ``` -------------------------------- ### Download and Unzip Tutorial Project Files (Windows) Source: https://holoviz.org/tutorial/Setup Downloads the HoloViz tutorial ZIP archive using PowerShell and extracts its contents to a 'holoviz_tutorial' directory. It then navigates into the extracted directory. This is specific to Windows environments. ```powershell Invoke-WebRequest -Uri "https://assets.holoviz.org/holoviz/tutorial/holoviz_tutorial.zip" -OutFile "holoviz_tutorial.zip" Expand-Archive -Path "holoviz_tutorial.zip" -DestinationPath "holoviz_tutorial" cd holoviz_tutorial ``` -------------------------------- ### Install Development Version Source: https://holoviz.org/contribute To test a development release, install the package using Conda from a development label. This allows for pre-release testing and verification of functionality before a final release. ```bash conda install -c pyviz/label/dev panel ``` -------------------------------- ### Create a Panel Row Layout Source: https://holoviz.org/tutorial/Dashboards Creates a Panel `Row` layout to arrange components horizontally. This example combines a Markdown title, a horizontal spacer, and a PNG logo. ```python header = pn.Row(dashboard_title, pn.layout.HSpacer(), pn.pane.PNG(logo_path, height=40, align='end')) header ``` -------------------------------- ### Check Data File Accessibility Source: https://holoviz.org/tutorial/Setup Uses a helper function 'check_data' to verify that a specific dataset file ('../data/earthquakes-projected.parq') exists and is readable. This ensures that the tutorial can access the necessary data. ```python from data_checker import check_data data_path = '../data/earthquakes-projected.parq' check_data(data_path) ``` -------------------------------- ### Python Warnings Module: warn Function Examples Source: https://holoviz.org/about/heps/hep2 Demonstrates the usage of Python's `warnings.warn` function and the impact of the `stacklevel` parameter on the warning output. Shows how to correctly identify the source of a warning in larger codebases. ```python # mod1.py import warnings def foo(): warnings.warn('The function foo is deprecated.') foo() ``` ```python # mod1.py import warnings def foo(): warnings.warn('The function foo is deprecated.', stacklevel=2) foo() ``` -------------------------------- ### Install Final Release Version Source: https://holoviz.org/contribute After a final release is made, install the package using Conda to perform final checks. This ensures the stable version is functioning as expected and free of critical issues. ```bash conda install -c pyviz panel ``` -------------------------------- ### Create a Panel Float Slider Widget Source: https://holoviz.org/tutorial/Interactive_Pipelines Demonstrates creating a Panel FloatSlider widget for selecting a minimum earthquake magnitude. The slider has a name, a start value, an end value, and an initial value. ```python mag_slider = pn.widgets.FloatSlider(name='Minimum Magnitude', start=0, end=9, value=6) mag_slider ``` -------------------------------- ### Get hvplot Help for Scatter Plots Source: https://holoviz.org/tutorial/Plotting Demonstrates how to use the `hvplot.help()` function to retrieve documentation for specific plot types, such as 'scatter'. This function displays a documentation pane within the notebook, detailing available options and parameters. ```python # hvplot.help('scatter') ``` -------------------------------- ### Load and Prepare Earthquake Data (Python) Source: https://holoviz.org/tutorial/exercises/Advanced_Dashboarding Loads earthquake data from a Parquet file into a Pandas DataFrame and times it. This is a starting point for building dashboards, allowing for subsequent filtering and visualization. ```Python %%time df = pd.read_parquet(pathlib.Path('../../data/earthquakes-projected.parq')) ``` -------------------------------- ### Apply Options to HoloViews Points Element with Specific Options Source: https://holoviz.org/tutorial/Custom_Interactivity Applies specific visual options, such as marker style, to a HoloViews `Points` element. This example shows how to use `.opts()` with parameters like `marker`. ```python import holoviews as hv import numpy as np hv.extension("bokeh") # Assuming 'esri' and 'most_severe' are defined elsewhere # esri * hv.Points(most_severe, ['easting', 'northing'], 'mag').opts(color='mag', size=8, aspect='equal', marker='+') ``` -------------------------------- ### Get hvplot Style Options Help Source: https://holoviz.org/tutorial/Plotting Retrieves specific documentation for the 'style' options of a 'scatter' plot using `hvplot.help()`. By setting `style=True` and `generic=False`, it filters the help output to show only style-related parameters that are directly passed to the Bokeh plotting backend. ```python # hvplot.help('scatter', style=True, generic=False) ``` -------------------------------- ### DeprecationWarning in Panel Apps Served with 'panel serve' Source: https://holoviz.org/about/heps/hep2 When serving a Panel application using `panel serve`, the module namespace of the served files is altered (e.g., `bokeh_app_`), not `__main__`. Consequently, `DeprecationWarning`s are typically not displayed. This example demonstrates a warning that won't be shown by default when served. ```python # app.py import warnings import panel as pn warnings.warn('Not displayed :(', DeprecationWarning) pn.panel('Hello world!').servable() ``` -------------------------------- ### Apply Visual Options to HoloViews Points Element Source: https://holoviz.org/tutorial/Custom_Interactivity Customizes the appearance of a HoloViews `Points` element using the `.opts()` method. This example sets the color based on a dimension, point size, enables a color bar, and sets the aspect ratio. ```python import holoviews as hv import numpy as np hv.extension("bokeh") xs = np.random.randn(100) ys = np.random.randn(100) fitness = np.random.randn(100) height_v_weight = hv.Points((xs, ys, fitness), ['weight', 'height'], 'fitness') height_v_weight.opts(color='fitness', size=8, colorbar=True, aspect='square') ``` -------------------------------- ### Run Panel Dashboard via Command Line Source: https://holoviz.org/tutorial/Dashboards Illustrates how to run the Panel dashboard application from the command line. This includes instructions for serving a Jupyter notebook as an app and for serving a Python script file. It also shows how to use `anaconda-project` to run the dashboard. ```bash # Serve a Jupyter notebook as an app panel serve --port 5067 06_Dashboards.ipynb # Serve a Python script file panel serve file.py # Using anaconda-project anaconda-project run dashboard ``` -------------------------------- ### Install pyctdev using Conda Source: https://holoviz.org/contribute Installs the pyctdev tool, a developer utility for HoloViz projects, using Conda. It specifies a minimum version requirement for pyctdev. ```shell conda install -c pyviz/label/dev "pyctdev>0.5.0" ``` -------------------------------- ### Create Panels using pn.panel Source: https://holoviz.org/tutorial/Dashboards Demonstrates using the `pn.panel` function to automatically create appropriate Panel pane objects (Markdown and PNG) from given inputs (string and file path). ```python dashboard_title = pn.panel('## Earthquakes') usgs_logo = pn.panel(logo_path, height=130) ``` -------------------------------- ### Declare TextInput Widget Source: https://holoviz.org/tutorial/Custom_Dashboards Declares a Panel TextInput widget for filtering data by place name. It includes a placeholder to guide user input. ```python place_filter = pn.widgets.TextInput(placeholder='Enter a placename') ``` -------------------------------- ### Import Libraries and Initialize Panel Extension Source: https://holoviz.org/tutorial/Dashboards Imports necessary libraries like pathlib, pandas, panel, xarray, holoviews, colorcet, and hvplot extensions. It also initializes the Panel extension with a 'bootstrap' template and 'tabulator' functionality. ```python import pathlib import pandas as pd import panel as pn import xarray as xr import holoviews as hv pn.extension('tabulator', template='bootstrap') import colorcet as cc import hvplot.xarray # noqa import hvplot.pandas # noqa ``` -------------------------------- ### HoloViews Object Notation Source: https://holoviz.org/tutorial/Composing_Plots Example of HoloViews notation for a Curve element. It indicates the element type ('Curve'), key dimension ('time'), and value dimension ('count'). ```text :Curve [time] (count) ``` -------------------------------- ### Serve Dashboard from Notebook Source: https://holoviz.org/tutorial/Dashboards Provides the command to serve the Panel dashboard as a standalone web application. This command is executed from the terminal. ```bash $ panel serve 06_Dashboards.ipynb ``` -------------------------------- ### Create a PNG Pane Source: https://holoviz.org/tutorial/Dashboards Creates a Panel PNG pane to display a PNG image. It takes a path to the image file as input and allows specifying the height. ```python logo_path = pathlib.Path('../assets/usgs_logo.png') pn.pane.PNG(logo_path, height=130) ``` -------------------------------- ### HoloViews Magnitude Plot Notation Source: https://holoviz.org/tutorial/Composing_Plots Example of HoloViews notation for the weekly mean magnitude plot. It specifies a 'Curve' element with 'time' as the key dimension and 'mag' as the value dimension. ```text :Curve [time] (mag) ``` -------------------------------- ### Declare RangeSlider Widget Source: https://holoviz.org/tutorial/Custom_Dashboards Declares a Panel RangeSlider widget for filtering data by magnitude. The widget's name, start, and end values are configured based on the loaded DataFrame. ```python mag_filter = pn.widgets.RangeSlider(name='Magnitude', start=0, end=df.mag.max()) ``` -------------------------------- ### Serve Panel Application Source: https://holoviz.org/tutorial/Dashboards Provides code snippets for serving the Panel application. The first snippet makes the widgets available in the sidebar, and the second serves the main dashboard layout with a specified title. These are typically used when running the application with `panel serve`. ```python pn.param.ReactiveExpr(filtered_table).widgets.servable(area='sidebar') ``` ```python column.servable(title='Earthquake Interactive Demo') ``` -------------------------------- ### Initialize Geo Data Visualization Components Source: https://holoviz.org/learn/presentations/Overview Sets up components for visualizing large geographic datasets, including map tiles, earthquake data loading with Dask, and colormap definitions. It uses EsriImagery for map tiles and reads parquet data for earthquakes. ```python import dask.dataframe as dd from colorcet import palette from holoviews.element.tiles import EsriImagery topts = hv.opts.Tiles(width=700, height=600, bgcolor='black', xaxis=None, yaxis=None, show_grid=False) tiles = EsriImagery().opts(topts) earthquakes = dd.read_parquet(Path('../../data/earthquakes-projected.parq'), engine='pyarrow').persist() colormaps = {n: palette[n] for n in ['fire','bgy','bgyw','bmy','gray','kbc']} ``` -------------------------------- ### Create a Markdown Pane Source: https://holoviz.org/tutorial/Dashboards Creates a Panel Markdown pane to display text formatted in Markdown. This is useful for adding titles or descriptions to dashboards. ```python pn.pane.Markdown('## Earthquake Dashboard') ``` -------------------------------- ### Inspect HoloViews Element Options with hv.help Source: https://holoviz.org/tutorial/Custom_Interactivity Demonstrates how to use `hv.help` to inspect the available style options for a HoloViews element type, such as `hv.Scatter`. This is useful for discovering customization possibilities. ```python # Commented as there is a lot of help output! # import holoviews as hv # hv.extension("bokeh") # hv.help(hv.Scatter) ``` -------------------------------- ### Assemble Dashboard Layout with Panel Source: https://holoviz.org/tutorial/Dashboards Constructs the final dashboard layout using Panel. It combines the interactive map visualization with widgets and other plots like histograms for magnitude and depth. It also sets up linked selections for interactive data exploration and configures the Panel template for serving the application. ```python pn.state.template.sidebar_width = 250 pn.state.template.title = 'Earthquake Interactive Demo' ls = hv.link_selections.instance(unselected_alpha=0.02) # Table is not yet dynamically linked to the linked selection filtered_table = filtered_subrange.pipe(ls.filter, selection_expr=ls.param.selection_expr)[['time', 'place', 'mag', 'depth']] table = pn.widgets.Tabulator( filtered_table, pagination='remote', page_size=10, show_index=False ) mag_hist = filtered_subrange.hvplot( y='mag', kind='hist', responsive=True, min_height=300, max_height=600, grid=True) depth_hist = filtered_subrange.hvplot( y='depth', kind='hist', responsive=True, min_height=300, max_height=600, grid=True) geo = filtered_subrange.hvplot( 'easting', 'northing', color='mag', kind='points', xaxis=None, yaxis=None, responsive=True, min_height=500, data_aspect=1, framewise=False, clim=(4, 10), line_color='black' ) column = pn.Column( pn.Row( hv.element.tiles.EsriImagery() * ls(hv.DynamicMap(geo)), ), pn.Row( table, ls(hv.DynamicMap(depth_hist)), ls(hv.DynamicMap(mag_hist)), ) ) ``` -------------------------------- ### Import Libraries for HoloViz Plotting Source: https://holoviz.org/tutorial/Interlinked_Plots Imports necessary libraries including pathlib for path manipulation, holoviews for plotting, pandas for data handling, hvplot.pandas for plotting integration, and colorcet for colormaps. This setup is crucial for generating interactive plots. ```python import pathlib import holoviews as hv import pandas as pd import hvplot.pandas # noqa import colorcet as cc ``` -------------------------------- ### Run unit tests Source: https://holoviz.org/contribute Executes the unit tests for the project. This command is typically run after making code changes to ensure functionality. ```shell doit test_unit. ``` -------------------------------- ### Create GitHub Release Source: https://holoviz.org/contribute After a successful release, create a corresponding GitHub Release. This involves navigating to the repository's Releases section, selecting the most recent tag, and adding release notes that mirror the changelog. ```github Go to the Github repository Click _Releases_ Click _Tags_ Click the most recent tag that you just added Click _Create a new release_ Add release notes and publish the release ``` -------------------------------- ### Declare Panel Widgets for Filtering Source: https://holoviz.org/tutorial/Dashboards Defines Panel widgets, specifically a DatetimeRangeSlider and a FloatSlider, to allow users to interactively filter the earthquake data by date and magnitude. The sliders are configured with appropriate start, end, and initial values derived from the data. ```python date_subrange = pn.widgets.DatetimeRangeSlider( name='Date', start=subset_df.time.iloc[0], end=subset_df.time.iloc[-1], max_width=400 ) mag_subrange = pn.widgets.FloatSlider(name='Magnitude', start=3, end=9, value=3, max_width=400) ``` -------------------------------- ### Render Plot with Matplotlib xkcd Style using hvplot.render Source: https://holoviz.org/tutorial/Plotting Renders a plot object and returns the underlying Matplotlib figure, allowing for advanced customization. This example applies Matplotlib's `xkcd` context manager to render the plot in a sketch-style. ```python import matplotlib.pyplot as plt with plt.xkcd(): mpl_fig = hvplot.render(plot) mpl_fig ``` -------------------------------- ### Create Interactive Geo-Spatial Visualization with hvplot Source: https://holoviz.org/tutorial/Dashboards Generates an interactive map visualization of earthquake data using hvplot. The visualization is linked to the defined Panel widgets, allowing real-time filtering of earthquakes based on magnitude and time. The map displays 'easting' and 'northing' coordinates, colored by magnitude, with ESRI tiles. ```python subset = pn.rx(subset_df) filtered_subrange = subset[ (subset['mag'] > mag_subrange) & (subset['time'] >= date_subrange.param.value_start) & (subset['time'] <= date_subrange.param.value_end) ] geo = filtered_subrange.hvplot( 'easting', 'northing', color='mag', kind='points', framewise=False, xaxis=None, yaxis=None, responsive=True, min_height=500, tiles='ESRI') ``` -------------------------------- ### Display Dashboard in a New Tab Source: https://holoviz.org/tutorial/Dashboards Shows the created Panel dashboard in a new browser tab. This method is used for quick viewing during development. ```python # mini_dashboard.show() ``` -------------------------------- ### Tagging and Pushing a Git Commit for Release Source: https://holoviz.org/contribute This snippet demonstrates the Git commands required to tag a commit for a new package version and push that tag to the remote repository. The tag format is crucial for triggering automated build processes. ```bash git tag -m "Version 1.9.6 alpha1" v1.9.6a1 main git push origin v1.9.6a1 ``` -------------------------------- ### Create Matplotlib Plot with HoloViews Source: https://holoviz.org/learn/presentations/Overview Generates a plot using HoloViews with the Matplotlib backend. This plot includes a vertical line and text annotation, similar to the Bokeh example, but results in a static image without interactivity. The `hv.output` function explicitly sets the backend. ```python mpl = by_state * hv.VLine(1963).opts(color="black") * \ hv.Text(1963, 1000, " Vaccine introduced", halign='left') hv.output(mpl, backend='matplotlib') ``` -------------------------------- ### Combine HoloViews Plots for Linked Visualization Source: https://holoviz.org/tutorial/Custom_Interactivity Combines multiple HoloViews plot components, including scatter plots, histograms, and vertical lines, into a single, linked visualization. This example demonstrates how to arrange these elements using HoloViews layout options like `+` for overlay and `.cols()` for arrangement. ```python ((esri * high_mag_quakes.opts(tools=['tap']) * labeller * quake_marker) + histogram + temporal_distribution * temporal_vline).cols(1) ``` -------------------------------- ### DeprecationWarning Display Based on Module Namespace and stacklevel Source: https://holoviz.org/about/heps/hep2 This example illustrates how DeprecationWarnings are displayed differently based on the module's namespace (`__main__` vs. others) and the `stacklevel` parameter. When a warning originates from a module not in `__main__` (like `mod2.py`), it might be filtered. `stacklevel` determines which calling line the warning is attributed to. ```python # mod1.py from mod2 import bottom, top print('Call top:') top() print('\nCall bottom:') bottom() ``` ```python # mod2.py import warnings def top(): return bottom() def bottom(): warnings.warn('bottom is deprecated', DeprecationWarning, stacklevel=2) ``` -------------------------------- ### Create Interactive App with Panel Interact Source: https://holoviz.org/learn/presentations/Overview Builds an interactive application using Panel's interact function, linking it to the earthquake visualization function. It creates widgets for colormap, alpha, and reverse colormap, and arranges them in a layout with a title. ```python import panel as pn explorer = pn.interact(view, cmap=colormaps, alpha=(0, 1.), reverse_colormap=False) pn.Row(pn.Column('# Earthquake Explorer', explorer[0]), explorer[1]).servable() ``` -------------------------------- ### Create Interactive Plots with hvPlot Source: https://holoviz.org/tutorial/Dashboards Generates two interactive plots using hvPlot: a scatter plot of earthquake magnitudes and a rasterized image plot of population density. These plots are configured to be responsive and have specific visual options. ```python sample_points = small_df.hvplot.points(x='longitude', y='latitude', c='mag', cmap=cc.CET_L4, responsive=True) rasterized_pop = cleaned_ds.hvplot.image(rasterize=True, logz=True, clim=(1, None), responsive=True, min_height=400).opts(bgcolor='black') earthquake_example = rasterized_pop * sample_points ``` -------------------------------- ### Create and Display a Date Range Slider Widget Source: https://holoviz.org/tutorial/Interactive_Pipelines Initializes and displays a Panel DatetimeRangeSlider widget, allowing users to select a date range. The widget's current value, represented as a tuple of start and end timestamps, can be accessed directly or via `value_start` and `value_end` parameters. ```python import panel as pn # Assuming df is a Pandas DataFrame with a DatetimeIndex date_widget = pn.widgets.DatetimeRangeSlider(name='Date', start=df.index[0], end=df.index[-1]) date_widget ``` -------------------------------- ### Create a Basic HoloViews Points Element Source: https://holoviz.org/tutorial/Custom_Interactivity Demonstrates the creation of a simple `Points` element in HoloViews. It generates random data for x and y coordinates and uses them to instantiate the `Points` element. ```python import holoviews as hv import numpy as np hv.extension("bokeh") xs = np.random.randn(100) ys = np.random.randn(100) hv.Points((xs, ys)) ``` -------------------------------- ### Filter and Visualize Large Datasets with Datashader Scatter Plot Source: https://holoviz.org/tutorial/Plotting Demonstrates filtering a large dataset before visualizing it with Datashader. This example selects earthquakes with magnitudes greater than 5 and plots them using a specific colormap ('Reds'). It utilizes `rasterize=True` for Datashader aggregation and `cnorm='eq_hist'` for colormap equalization. ```python df[df.mag>5].hvplot.scatter(x='longitude', y='latitude', rasterize=True, cnorm='eq_hist', cmap='Reds') ``` -------------------------------- ### Bind Population Calculation and Display with Panel Source: https://holoviz.org/tutorial/Advanced_Dashboards Connects the `affected_population` function to Panel streams and widgets using `pn.bind`. It also creates a `hv.DynamicMap` for `bounds` and combines these with other HoloViews elements for display. This setup allows for a dynamic visualization that updates population estimates and geographic bounds based on user interaction with streams and widgets. ```python dynamic_bounds = hv.DynamicMap(bounds, streams=[index_stream, dist_slider.param.value]) bound_affected_population = pn.bind(affected_population, index=index_stream.param.index, distance=dist_slider) pn.Column(pn.panel(bound_affected_population, width=400), rasterized_pop * high_mag_points * dynamic_bounds, dist_slider) ``` -------------------------------- ### Load and Sample Earthquake Data Source: https://holoviz.org/tutorial/Dashboards Loads earthquake data from a Parquet file into a pandas DataFrame and resets the index. It then samples a small fraction of the data for plotting. ```python %%time df = pd.read_parquet(pathlib.Path('../data/earthquakes-projected.parq')) df.index = df.index.tz_localize(None) df = df.reset_index() small_df = df.sample(frac=.01) ``` -------------------------------- ### Initialize Panel Extension Source: https://holoviz.org/tutorial/Custom_Dashboards Initializes the Panel extension for use in a Jupyter environment. This is a prerequisite for most Panel applications. ```python import pathlib import panel as pn pn.extension() ``` -------------------------------- ### Create Panel Number Indicator from Reactive Expression Source: https://holoviz.org/tutorial/Interactive_Pipelines This example shows how to pass a reactive expression directly to a Panel component. Here, the maximum value of the 'mag' column from a filtered dataset (a reactive expression) is computed and passed as the 'value' to a 'pn.indicators.Number' widget. This allows Panel components to efficiently re-render when the underlying expression's value changes. ```python pn.indicators.Number(value=filtered_subrange.mag.max(), name='Magnitude') ``` -------------------------------- ### Create Interactive Adder Component Source: https://holoviz.org/tutorial/Custom_Dashboards Declares two IntInput widgets and a function that adds their values. It then lays out the widgets and the result of the addition using pn.bind, creating a simple interactive calculator. ```python w1 = pn.widgets.IntInput(value=1, width=60) w2 = pn.widgets.IntInput(value=1, width=60) def adder(v1, v2): return pn.panel(v1 + v2, width=50) pn.Row(w1, '+', w2, '=', pn.bind(adder, v1=w1, v2=w2)) ``` -------------------------------- ### Load and Prepare Earthquake Data Source: https://holoviz.org/tutorial/exercises/Building_a_Dashboard Loads the earthquake dataset from a Parquet file, selects relevant columns, and filters for the most severe earthquakes (magnitude >= 7). This prepares the data for visualization. ```python %%time df = pd.read_parquet(pathlib.Path('../../data/earthquakes-projected.parq')) columns = ['mag', 'depth', 'latitude', 'longitude', 'place', 'type'] df = df[columns] most_severe = df[df.mag >= 7] ``` -------------------------------- ### Import Libraries for HoloViz Dashboard Source: https://holoviz.org/tutorial/exercises/Building_a_Dashboard Imports necessary libraries including pathlib, numpy, pandas, and panel for building interactive dashboards. It also initializes Panel extensions and imports hvplot for plotting. ```python import pathlib import numpy as np import pandas as pd import panel as pn pn.extension('katex') import hvplot.pandas # noqa ``` -------------------------------- ### Create Richter Scale Equation Panel Component Source: https://holoviz.org/tutorial/exercises/Building_a_Dashboard Creates a Panel component to display the mathematical equation for the Richter scale using LaTeX formatting. This ensures the equation is rendered correctly with proper mathematical notation. ```python equation_string = '$M_L = log_{10}A - log_{10} A_0(delta)$' ## Define a panel component containing the equation (Hint: Use the LaTeX pane) equation = ... ## Display it equation = pn.pane.LaTeX(equation_string) equation ``` -------------------------------- ### Compose Static Dashboard Layout Source: https://holoviz.org/tutorial/exercises/Building_a_Dashboard Arranges previously defined Panel components (logo, equation, strongest_earthquakes, gmap, plot) into a static dashboard layout using `pn.Row` and `pn.Column`. Includes headers and spacing for a structured presentation. ```python # Static Dashboard combining all the elements above. year = 2000 logo = pn.panel(logo_url, width=200) equation = pn.pane.LaTeX(equation_string) strongest_earthquakes = strongest_earthquakes_fn(year) gmap = pn.pane.HTML(gmap_fn(year), height=300, width=300) year_df = df[(df.index.index.year == year) & (df.mag > 7)] plot = year_df.hvplot.line(x='time', y='mag') title = pn.panel('# Strongest Earthquakes in the Year %d' % year, width=400) header = pn.Row(title, pn.layout.HSpacer(), logo) body_row1 = pn.Row( pn.Column('### Richter scale definition', equation, '### Strongest Earthquake', gmap), pn.Column('### Strongest Earthquakes', strongest_earthquakes), ) pn.Column(header, pn.Column(body_row1,pn.Column('### Magnitude Plot', plot))) ``` -------------------------------- ### Initialize hvplot Explorer with DataFrame Source: https://holoviz.org/tutorial/Plotting This code snippet shows how to initialize the hvPlot Explorer by passing a DataFrame (e.g., 'small_df') to the `hvplot.explorer` function. This action generates an interactive Panel layout for data exploration. ```python hvplot.explorer(small_df) ```