### Install Arakawa using pip
Source: https://ninoseki.github.io/arakawa/latest/quickstart
Installs the Arakawa library using pip. Ensure you have Python and pip installed.
```bash
pip3 install -U arakawa
```
--------------------------------
### Load Iris Dataset and Get Columns
Source: https://ninoseki.github.io/arakawa/latest/quickstart
Loads the Iris dataset from vega_datasets and extracts the column names. This prepares the data for visualization and Arakawa blocks.
```python
df = data.iris()
columns = list(df.columns)
print(columns)
```
--------------------------------
### Import Libraries for Arakawa Report
Source: https://ninoseki.github.io/arakawa/latest/quickstart
Imports necessary libraries: altair for plotting, arakawa for report generation, and vega_datasets for sample data.
```python
import altair as alt
import arakawa as ar
from vega_datasets import data
```
--------------------------------
### Save Arakawa Report to HTML
Source: https://ninoseki.github.io/arakawa/latest/quickstart
Saves the generated Arakawa view as an HTML report and optionally opens it in a new window. This function is key for sharing Arakawa reports.
```python
ar.save_report(view, "quickstart_report.html", open=True)
# or
ar.Report(view).save("quickstart_report.html", open=True)
```
--------------------------------
### Create Altair Scatterplot and Arakawa View
Source: https://ninoseki.github.io/arakawa/latest/quickstart
Generates an Altair scatterplot of the Iris dataset and creates an Arakawa view containing the plot and a data table. This demonstrates Arakawa's block system for organizing report content.
```python
fig = (
alt.Chart(df)
.mark_point()
.encode(x=alt.X("sepalLength", scale=alt.Scale(zero=False)),
y=alt.X("sepalWidth", scale=alt.Scale(zero=False)),
color="species")
)
view = ar.Select(ar.Plot(fig, label="Plot"), ar.DataTable(df, label="Data"))
view
```
--------------------------------
### Install Arakawa with Extra Dependencies
Source: https://ninoseki.github.io/arakawa/latest/installing-arakawa
Installs Arakawa with optional extra dependencies for enhanced functionality. Available extras include 'dataframing' (Polars), 'network' (NetworkX), 'plotting' (Bokeh, Folium, Matplotlib, Plotly), and 'tabling' (Great Tables). 'all' installs all extras.
```shell
pip install arakawa[dataframing]
pip install arakawa[network]
pip install arakawa[plotting]
pip install arakawa[tabling]
# install all the extra dependencies
pip install arakawa[all]
```
--------------------------------
### Install Arakawa using Pip
Source: https://ninoseki.github.io/arakawa/latest/installing-arakawa
Installs or upgrades the Arakawa Python library using pip. This is the recommended method for installation and upgrading. Ensure you have Python 3.10-3.13 installed.
```shell
pip install -U arakawa
```
```python
!pip install -U arakawa
```
--------------------------------
### Create a Compute Block with Form Controls
Source: https://ninoseki.github.io/arakawa/latest/blocks/layout-blocks
Shows how to use the `ar.Compute` block to compose an HTML form. This example includes a text input (`ar.TextBox`) and a number input (`ar.NumberBox`), demonstrating how to gather user input.
```python
ar.Compute(
ar.TextBox("text"),
ar.NumberBox("number")
)
```
--------------------------------
### Import Arakawa and Data Libraries for Jupyter
Source: https://ninoseki.github.io/arakawa/latest/reports/jupyter-integration
Initializes the necessary libraries for using Arakawa within a Jupyter Notebook environment. This setup is foundational for all subsequent Arakawa functionalities.
```python
import arakawa as ar
import altair as alt
from vega_datasets import data
```
--------------------------------
### BigNumber Basic Usage Example
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Demonstrates the basic usage of the BigNumber component to display a single statistic. It requires a heading and a value. The output will show the heading followed by the value.
```python
ar.BigNumber(heading="Simple Statistic", value=100)
```
--------------------------------
### Nesting Layout Blocks for Complex UIs
Source: https://ninoseki.github.io/arakawa/latest/blocks/layout-blocks
Demonstrates how `ar.Group` and `ar.Select` blocks can be nested to create complex user interfaces. This example shows a two-column layout where one column contains a tabbed interface with text content. This showcases the flexibility of layout blocks.
```python
ar.Group(
ar.Text("This is the left side of a two-column layout"),
ar.Group(
ar.Text("This is the right side of a two-column layout"),
ar.Text("Below we have three tabs with different content"),
ar.Select(
blocks=[
ar.Text("Hello World 1", label="Page 1"),
ar.Text("Hello World 2", label="Page 2"),
ar.Text("Hello World 3", label="Page 3"),
]
),
),
columns=2,
)
```
--------------------------------
### Install Arakawa using Conda
Source: https://ninoseki.github.io/arakawa/latest/installing-arakawa
Installs Arakawa using conda. Note: The conda package is not yet released, and users are advised to use pip. If issues arise, consider updating all conda packages or creating a new environment.
```shell
conda install -c conda-forge arakawa
```
```python
!conda install -c conda-forge arakawa
```
--------------------------------
### BigNumber With Change Indicators Example
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Illustrates how to use the BigNumber component to show changes and their direction. This example includes scenarios for percentage changes and point changes, both for upward and downward trends. The `is_upward_change` parameter is crucial for determining the color and indicator of the change. This snippet is wrapped in a Group for better layout.
```python
ar.Group(
ar.BigNumber(
heading="Percentage points",
value="84%",
change="2%",
is_upward_change=True,
),
ar.BigNumber(
heading="Percentage points",
value="84%",
change="2%",
is_upward_change=False,
),
ar.BigNumber(
heading="Points",
value="1234",
change="200",
is_upward_change=True,
),
ar.BigNumber(
heading="Points",
value="1234",
change="200",
is_upward_change=False,
),
columns=2,
)
```
--------------------------------
### Save and Stringify Arakawa Reports in Python
Source: https://ninoseki.github.io/arakawa/latest/reference/reports
This snippet demonstrates the basic usage of the arakawa library to create a report with text and save it as an HTML file or get its HTML string representation. It requires the 'arakawa' library to be installed.
```python
import arakawa as ar
report = ar.Report(ar.Text("Hello, world!"))
report.save("report.html")
# or
report.stringify()
```
--------------------------------
### Create Simple Toggle with Titanic Data (Python)
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/toggle
Demonstrates how to create a simple Toggle component in Python using the arakawa library. This example loads the Titanic dataset, creates an HTML image, and includes a Toggle containing a data description table, the full dataset table, and the source code. The Toggle's visibility can be controlled by the report viewer.
```python
import seaborn as sns
code = """
titanic = sns.load_dataset("titanic")
report = ar.Report(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Select(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
]
),
)
report.save(path="select.html")
"""
titanic = sns.load_dataset("titanic")
ar.Blocks(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Toggle(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
]
),
)
```
--------------------------------
### FileField Usage Example in Python
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/file
This snippet demonstrates how to instantiate a FileField in Python. The FileField is used to create a file input element in a form, with a required 'name' parameter. Additional optional parameters allow for help text, labels, validation, and specifying accepted file types.
```python
ar.FileField("file")
```
--------------------------------
### Upgrade Arakawa using Conda
Source: https://ninoseki.github.io/arakawa/latest/installing-arakawa
Upgrades an existing Arakawa installation managed by conda. The conda package is not yet released. If issues occur, try updating all packages or using a new conda environment.
```shell
conda update arakawa
# or
conda update --all
```
--------------------------------
### Embed YouTube Video using Arakawa Embed Block
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/embeds
This example shows how to embed a YouTube video using the `ar.Embed` block. The block takes a URL of the resource to be embedded and optional parameters for `width`, `height`, `name`, and `label`. For simple embeds like GIFs, Markdown syntax `` can be used instead.
```python
ar.Embed(url='https://www.youtube.com/watch?v=_KS_yZBI71s&t')
```
--------------------------------
### Create Altair Plot
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/plots
Embed an interactive Altair plot in your Arakawa application. Altair is a declarative statistical visualization library. This example demonstrates creating a scatter plot with interactive filtering based on a year slider.
```python
import altair as alt
import pandas as pd
from vega_datasets import data as vega_data
gap = pd.read_json(vega_data.gapminder.url)
select_year = alt.selection_point(
name="select",
fields=["year"],
value={"year": 1955},
bind=alt.binding_range(min=1955, max=2005, step=5),
)
alt_chart = (
alt.Chart(gap)
.mark_point(filled=True)
.encode(
alt.X("fertility", scale=alt.Scale(zero=False)),
alt.Y("life_expect", scale=alt.Scale(zero=False)),
alt.Size("pop:Q"),
alt.Color("cluster:N"),
alt.Order("pop:Q", sort="descending"),
)
.add_params(select_year)
.transform_filter(select_year)
)
ar.Plot(alt_chart)
```
--------------------------------
### Attach Python Dictionary using Arakawa Attachment Block
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/embeds
This example shows how to attach a Python dictionary directly to an Arakawa report using the `ar.Attachment` block. The dictionary is saved as a data file that users can download. The `data` parameter accepts a Python object, and `name` can be used to specify a unique name for the block.
```python
vehicle_dict = {"brand": "Ford", "model": "Mustang", "year": 1964}
ar.Attachment(vehicle_dict, name="vehicle_dict")
```
--------------------------------
### Create HTML Form with Compute and Blocks - Python
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/compute
This snippet demonstrates how to use the `Compute` class in Python to create an HTML form. It takes several optional parameters for form customization and accepts a list of block elements like `TextBox` and `NumberBox`. The `method` parameter specifies the HTTP method for form submission.
```python
ar.Compute(
subtitle="Subtitle",
label="Label",
method="POST",
blocks=[
ar.TextBox("text", required=True),
ar.NumberBox("number", initial=100),
],
)
```
--------------------------------
### Create a Select Block with Multiple Text Pages
Source: https://ninoseki.github.io/arakawa/latest/blocks/layout-blocks
Illustrates the creation of an `ar.Select` block that acts as a tabbed interface. Each tab displays different text content using `ar.Text` blocks. This is an interactive element that does not require a backend.
```python
ar.Select(
blocks=[
ar.Text("Hello World 1", label="Page 1"),
ar.Text("Hello World 2", label="Page 2"),
ar.Text("Hello World 3", label="Page 3"),
]
)
```
--------------------------------
### Implement ChoiceField Select Input with Python
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/choices
The ChoiceField enables the creation of a select dropdown input. It requires 'name' and 'options' parameters. Optional parameters include help text, initial value, label, required status, and validation rules.
```python
ar.ChoiceField("choice", ["a", "b"])
```
--------------------------------
### Create Bokeh Plot
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/plots
Embed an interactive Bokeh plot in your Arakawa application. Bokeh is known for its elegant construction of versatile graphics and high-performance interactivity. This example creates a scatter plot of Iris flower data.
```python
from bokeh.plotting import figure
from bokeh.sampledata.iris import flowers
colormap = {"setosa": "red", "versicolor": "green", "virginica": "blue"}
colors = [colormap[x] for x in flowers["species"]]
bokeh_chart = figure(title="Iris Morphology")
bokeh_chart.xaxis.axis_label = "Petal Length"
bokeh_chart.yaxis.axis_label = "Petal Width"
bokeh_chart.circle(
flowers["petal_length"],
flowers["petal_width"],
color=colors,
fill_alpha=0.2,
size=10,
)
ar.Plot(bokeh_chart)
```
--------------------------------
### Create Plotly Plot
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/plots
Embed an interactive Plotly plot in your Arakawa application. Plotly's Python library creates interactive, publication-quality graphs. This example generates a scatter plot of world data for the year 2007.
```python
import plotly.express as px
df = px.data.gapminder()
plotly_chart = px.scatter(
df.query("year==2007"),
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
hover_name="country",
log_x=True,
size_max=60,
)
ar.Plot(plotly_chart)
```
--------------------------------
### Arakawa TextBox Validation Example
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/validation
Demonstrates how to apply custom validation rules to an Arakawa TextBox. It uses Formkit's pipe-separated string format for defining validation logic, specifically ensuring the input is a number within a specified range.
```python
ar.TextBox("text", validation="number|between:20,50", help="Enter a number between 20 and 50")
```
--------------------------------
### Create a 2-Column Grid with Plot and DataTable
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/group
Shows how to combine a visual plot (created with Altair) and a data table within a two-column grid using the `Group` block. This requires the `altair` and `vega_datasets` libraries.
```python
import altair as alt
from vega_datasets import data
df = data.iris()
plot = (
alt.Chart(df)
.mark_point()
.encode(x="petalLength:Q", y="petalWidth:Q", color="species:N")
)
ar.Group(ar.Plot(plot), ar.DataTable(df), columns=2)
```
--------------------------------
### Create Matplotlib Plot
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/plots
Embed a Matplotlib plot in your Arakawa application. Note that Matplotlib plots are not interactive in Arakawa apps but are saved as high-fidelity SVGs. This example creates a scatter plot using Pandas plotting capabilities, which leverages Matplotlib.
```python
import matplotlib.pyplot as plt
import pandas as pd
from vega_datasets import data as vega_data
gap = pd.read_json(vega_data.gapminder.url)
fig = gap.plot.scatter(x="life_expect", y="fertility")
ar.Plot(fig)
```
--------------------------------
### Create Select Component with Tabs - Python
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/select
Demonstrates how to create a Select component using tabs to display different data representations (description, full dataset, source code) of the Titanic dataset. This snippet utilizes the `ar.Select` block with `ar.SelectType.TABS` implicitly or explicitly.
```python
import seaborn as sns
code = """
titanic = sns.load_dataset("titanic")
report = ar.Report(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Select(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
]
),
)
app.save(path="select.html")
"""
titanic = sns.load_dataset("titanic")
ar.Blocks(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Select(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
]
),
)
```
--------------------------------
### Create a Simple 2-Column Grid with Text
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/group
Demonstrates the basic usage of the `Group` block to create a two-column layout containing simple text elements. This is useful for side-by-side content presentation.
```python
ar.Group(ar.Text("⬅️ Left side"), ar.Text("➡️ Right side"), columns=2)
```
--------------------------------
### Create Simple Markdown Text with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
Renders a simple string as Markdown text. This is the most basic usage of the Text block. It takes a single string argument.
```python
ar.Text("__My awesome markdown__")
```
--------------------------------
### Populate a 2-Column Grid from a List of Blocks
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/group
Illustrates how to dynamically populate a two-column grid by passing a list of blocks to the `Group` block's `blocks` parameter. This method is suitable for generating content programmatically or handling numerous blocks.
```python
import altair as alt
from vega_datasets import data
df = data.iris()
plot = (
alt.Chart(df)
.mark_point()
.encode(x="petalLength:Q", y="petalWidth:Q", color="species:N")
)
# You could also generate these in a loop/function
my_plots = [ar.Plot(plot), ar.DataTable(df)]
ar.Group(blocks=my_plots, columns=2)
```
--------------------------------
### Generate Interactive Report with Arakawa Blocks
Source: https://ninoseki.github.io/arakawa/latest/blocks/overview
This Python script demonstrates how to create an interactive report using Arakawa. It utilizes Altair for plotting, Arakawa's layout blocks (Page, Group, Select) and display blocks (Formula, BigNumber, Plot, HTML, DataTable) to construct a multi-page report with interactive elements and visualizations. The report is then saved as an HTML file.
```python
# Import libraries
import arakawa as ar
import altair as alt
from vega_datasets import data
# Load the data from vega_datasets
source = data.cars()
# Create an interactive Altair chart
plot1 = (
alt.Chart(source)
.mark_circle(size=60)
.encode(
x="Horsepower",
y="Miles_per_Gallon",
color="Origin",
tooltip=["Name", "Origin", "Horsepower", "Miles_per_Gallon"],
)
.interactive()
)
report = ar.Blocks(
ar.Page(
title="Plots",
blocks=[
ar.Formula("x^2 + y^2 = z^2"),
ar.Group(
ar.BigNumber(heading="Number of percentage points", value="84%", change="2%", is_upward_change=True),
ar.BigNumber(heading="Simple Statistic", value=100),
columns=2,
),
ar.Select(
ar.Plot(plot1, label="Chart"),
ar.HTML(
"""
via GIPHY
""",
label="HTML + GIF",
),
),
],
),
ar.Page(title="Data", blocks=[ar.DataTable(source, label="Data")]),
)
ar.save_report(report, path='report.html')
```
--------------------------------
### Create Iris Analysis Plot with Group and Select
Source: https://ninoseki.github.io/arakawa/latest/blocks/layout-blocks
Demonstrates using `ar.Group` and `ar.Select` to create an interactive Iris dataset analysis. It displays a data table and two plots, allowing users to select and view different visual representations of the data. Requires `altair` and `vega_datasets` libraries.
```python
import altair as alt
from vega_datasets import data
df = data.iris()
plot_base = alt.Chart(df).mark_point().interactive()
ar.Group(
"Iris analysis",
ar.Select(
ar.DataTable(df, label='Data'),
ar.Group(
ar.Plot(plot_base.encode(x='sepalLength', y='sepalWidth', color='species')),
ar.Plot(plot_base.encode(x='petalLength', y='petalWidth', color='species')),
columns=2,
label='Plots'
)
)
)
```
--------------------------------
### Load Markdown Text from File with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
Loads Markdown content from a specified file path. This is useful for separating content from code, allowing articles or posts to be written in external Markdown editors. It takes a `file` parameter with the path to the Markdown file.
```python
ar.Text(file="./my_blogpost.md").format(plot=points)
```
--------------------------------
### Create Arakawa Pages with Altair and Seaborn Data
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/page
This Python snippet demonstrates how to create two Arakawa pages, 'Titanic Dataset' and 'Titanic Plot'. The 'Titanic Dataset' page displays a dataset, while the 'Titanic Plot' page visualizes it using an Altair chart generated from Seaborn data. It utilizes 'ar.Page' to define each page and 'ar.Blocks' to group them.
```python
import altair as alt
import seaborn as sns
titanic = sns.load_dataset("titanic")
points = (
alt.Chart(titanic)
.mark_point()
.encode(
x="age:Q",
color="class:N",
y="fare:Q",
)
.interactive()
.properties(width="container")
)
ar.Blocks(
ar.Page(title="Titanic Dataset", blocks=["### Dataset", titanic]),
ar.Page(title="Titanic Plot", blocks=["### Plot", points]),
)
```
--------------------------------
### Create SearchField Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding a search type input field. It takes a single string argument for the input's name.
```python
ar.SearchField("search")
```
--------------------------------
### Create Select Component with Dropdown - Python
Source: https://ninoseki.github.io/arakawa/latest/reference/layout-blocks/select
Demonstrates how to create a Select component using a dropdown to display different data representations of the Titanic dataset. This snippet explicitly sets the `type` parameter to `ar.SelectType.DROPDOWN`.
```python
import seaborn as sns
code = """
titanic = sns.load_dataset("titanic")
report = ar.Report(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Select(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
]
),
)
report.save(path="select.html")
"""
titanic = sns.load_dataset("titanic")
ar.Blocks(
"# Titanic overview",
ar.HTML(
'
'
),
ar.Select(
blocks=[
ar.Table(titanic.describe(), label="Data Description"),
ar.DataTable(titanic, label="Whole Dataset"),
ar.Code(code, label="Source code"),
],
type=ar.SelectType.DROPDOWN,
),
)
```
--------------------------------
### Import Arakawa Library
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/validation
Imports the necessary arakawa library for use in the project. This is a foundational step before utilizing any Arakawa components.
```python
import arakawa as ar
```
--------------------------------
### Display BigNumber Blocks in a Group Layout
Source: https://ninoseki.github.io/arakawa/latest/blocks/layout-blocks
Shows how to use `ar.Group` to display multiple `ar.BigNumber` blocks with headings and values. This layout is useful for presenting key metrics or summary statistics. Supports arranging blocks in a specified number of columns.
```python
ar.Group(
ar.BigNumber(heading="Left", value="1234"),
ar.BigNumber(heading="Middle", value="4321"),
ar.BigNumber(heading="Right", value="2314"),
columns=3,
)
```
--------------------------------
### Embed Blocks in Markdown Text with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
Allows embedding other Arakawa blocks within a Markdown string using double brace placeholders like {{block_name}}. This is useful for text-heavy applications like blog posts, enabling dynamic content insertion. It uses the `.format()` method to pass in the blocks.
```python
import seaborn as sns
import altair as alt
md = """
For example, if we want to visualize the number of people in each class within the interval we select a point chart between age and fare, we could do something like this.
{{plot}}
Altair allows you to create some extremely interactive plots which do on-the-fly calculations — without even requiring a running Python server!
"""
titanic = sns.load_dataset("titanic")
points = (
alt.Chart(titanic)
.mark_point()
.encode(
x="age:Q",
color="class:N",
y="fare:Q",
)
.interactive()
.properties(width="container")
)
ar.Text(md).format(plot=points)
```
--------------------------------
### Visualize Sigma.js Network Graph Data with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/blocks/display-blocks
This code snippet demonstrates how to visualize network graph data using Arakawa's Sigma block. It loads graph data from a JSON file, preprocesses node sizes, and configures layout settings for sigma.js rendering. This block is for direct sigma.js graph data.
```python
import json
with open("./artic.json") as f:
data = json.load(f)
max_size = max([node_data["attributes"]["size"] for node_data in data["nodes"]])
for node_data in data["nodes"]:
node_data["attributes"]["size"] /= max_size
node_data["attributes"]["size"] *= 20
node_data["attributes"]["size"] += 5
ar.Sigma(
data,
layout_settings={
"outbound_attraction_distribution": True,
"barnes_hut_optimize": True,
"adjust_sizes": True,
"lin_log_mode": True,
},
)
```
--------------------------------
### Display Alert Messages with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/blocks/display-blocks
Shows how to display alert messages using Arakawa. The `ar.Alert` function allows for customizable alert messages with different modes, such as WARNING, INFO, SUCCESS, and ERROR.
```python
ar.Alert("This is an alert", mode=ar.AlertMode.WARNING)
```
--------------------------------
### Create TextBox Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding a text type input field. It takes a single string argument for the input's name.
```python
ar.TextBox("text")
```
--------------------------------
### Create Simple Table From DataFrame using ar.Table
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Generates a basic HTML table from a pandas DataFrame. This is suitable for displaying multidimensional data without flattening. It takes a pandas DataFrame as input and optionally a caption, name, and label for the block.
```python
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"A": np.random.normal(-1, 1, 5),
"B": np.random.normal(1, 2, 5),
}
)
ar.Table(df)
```
--------------------------------
### Create Multi-line Markdown Text with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
Renders multi-line Markdown text using triple-quoted strings. This allows for complex formatting and embedding of code blocks within the Markdown content. It accepts a string argument containing the Markdown.
```python
md = """Quas *diva coeperat usum*; suisque, ab alii, prato. Et cornua frontes puerum,
referam vocassent **umeris**. Dies nec suorum alis adstitit, *temeraria*,
anhelis aliis lacunabant quoque adhuc spissatus illum refugam perterrita in
sonus. Facturus ad montes victima fluctus undae Zancle et nulli; frigida me.
Regno memini concedant argento Aiacis terga, foribusque audit Persephone
serieque, obsidis cupidine qualibet Exadius.
```python
utf_torrent_flash = -1;
urlUpnp -= leakWebE - dslam;
skinCdLdap += sessionCyberspace;
var ascii = address - software_compile;
webFlaming(cable, pathIllegalHtml);
```
## Quo exul exsecrere cuique non alti caerulaque
*Optatae o*! Quo et callida et caeleste amorem: nocet recentibus causamque.
- Voce adduntque
- Divesque quam exstinctum revulsus
- Et utrique eunti
- Vos tantum quercum fervet et nec
- Eris pennis maneas quam
"""
ar.Text(md)
```
--------------------------------
### Implement MultiChoiceField Multiple Select Input with Python
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/choices
The MultiChoiceField provides a multiple select input functionality. It requires 'name', 'initial' (list of strings), and 'options' (list of strings). Optional parameters cover help text, label, required status, and validation.
```python
ar.MultiChoiceField("multi-choice", ["a", "b"], ["a", "b", "c"])
```
--------------------------------
### Implement TagsField Multi Select with Free Form Input in Python
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/choices
The TagsField allows for a multi-select input combined with free-form text entry for tags. It requires 'name' and 'initial' (list of strings). Optional parameters include help text, label, required status, and validation.
```python
ar.TagsField("tags", ["a", "b"])
```
--------------------------------
### Sigma Network Visualization
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/network
The `Sigma` component visualizes network data using Sigma.js and Graphology. It accepts graph data in a dictionary format and allows for layout customization via `layout_settings`.
```APIDOC
## Sigma Network Visualization
### Description
This component renders a network graph using Sigma.js and Graphology. It requires graph data and supports customizable layout settings.
### Method
`ar.Sigma(
data: dict[str, Any],
width: int = 960,
height: int = 540,
layout_settings: LayoutSettings | None = None,
name: str | None = None,
label: str | None = None
)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **data** (dict[str, Any]) - Required - A Sigma/Graphology graph data to attach.
- **width** (int) - Optional - A width of the graph. Default: 960.
- **height** (int) - Optional - A height of the graph. Default: 540.
- **layout_settings** (LayoutSettings | None) - Optional - Settings for the ForceAtlas2 layout. See https://www.npmjs.com/package/graphology-layout-forceatlas2#settings (each key should be snake_cased). Default: None.
- **name** (str | None) - Optional - A unique name for the block to reference when adding text or embedding. Default: None.
- **label** (str | None) - Optional - A label used when displaying the block. Default: None.
### Request Example
```json
{
"data": {
"options": {"type": "mixed", "multi": False, "allowSelfLoops": True},
"attributes": {},
"nodes": [
{
"key": "A",
"attributes": {"label": "A", "size": 20}
},
{"key": "B", "attributes": {"label": "B", "size": 20}}
],
"edges": [{"key": "geid_179_0", "source": "A", "target": "B"}]
}
}
```
### Response
#### Success Response (200)
This component renders a visualization and does not return a JSON response.
#### Response Example
None
```
--------------------------------
### Embed HTML Content with Arakawa
Source: https://ninoseki.github.io/arakawa/latest/blocks/display-blocks
Illustrates embedding raw HTML content into an Arakawa application. The `ar.HTML` function takes an HTML string as input and renders it directly in the application. This is useful for including custom layouts, styles, and dynamic content.
```python
html = """
Welcome to my App
"""
ar.HTML(html)
```
--------------------------------
### Run SQL Query on DataTable
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Allows running SQL queries directly on a DataTable for advanced filtering and calculations. The special keyword `$table` is used as a placeholder for the DataTable's data within the query.
```sql
SELECT *
FROM $table
WHERE A > 0.5
```
--------------------------------
### Display Alerts
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
The Alert block displays messages with optional borders and modes (e.g., DANGER). Text can be formatted using Markdown. Parameters include the text content, border status, alert mode, and optional name/label.
```python
ar.Alert("Danger!", mode=ar.AlertMode.DANGER)
```
--------------------------------
### Generate Arakawa Report with Altair Plot and Data Table (Python)
Source: https://ninoseki.github.io/arakawa/latest/reports/overview
This snippet demonstrates how to create an Arakawa Report containing a heading, an interactive Altair plot, and an interactive data table. It requires the 'arakawa', 'altair', and 'vega_datasets' libraries. The output is an 'ar.Blocks' object ready for saving as a report.
```python
import altair as alt
import arakawa as ar
from vega_datasets import data
df = data.iris()
fig = (
alt.Chart(df)
.mark_point()
.encode(x="petalLength", y="petalWidth", color="species")
)
view = ar.Blocks("# My report", ar.Plot(fig), ar.DataTable(df))
```
--------------------------------
### Create EmailField Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding an email type input field. It takes a single string argument for the input's name.
```python
ar.EmailField("email")
```
--------------------------------
### Embed Syntax-Highlighted Code (Python, JavaScript)
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/text
The Code block embeds syntax-highlighted source code. It supports Python and JavaScript, with Python as the default language. Parameters include the code itself, language, an optional caption, and a unique name for referencing.
```python
code = """
function foo(n) {
return foo(n + 1)
}
"""
ar.Code(code=code, language="javascript")
```
```javascript
function foo(n) {
return foo(n + 1)
}
```
--------------------------------
### Create URLField Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding a URL type input field. It takes a single string argument for the input's name.
```python
ar.URLField("url")
```
--------------------------------
### Create Great Table From DataFrame using ar.GreatTables
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Generates a visually appealing table from a pandas DataFrame using the `great_tables` library. It supports advanced formatting for headers, currency, dates, and numbers, and allows hiding columns. It requires a GT object as input.
```python
from great_tables import GT
from great_tables.data import sp500
# Define the start and end dates for the data range
start_date = "2010-06-07"
end_date = "2010-06-14"
# Filter sp500 using Pandas to dates between `start_date` and `end_date`
sp500_mini = sp500[(sp500["date"] >= start_date) & (sp500["date"] <= end_date)]
# Create a display table based on the `sp500_mini` table data
gt = (
GT(sp500_mini)
.tab_header(title="S&P 500", subtitle=f"{start_date} to {end_date}")
.fmt_currency(columns=["open", "high", "low", "close"])
.fmt_date(columns="date", date_style="wd_m_day_year")
.fmt_number(columns="volume", compact=True)
.cols_hide(columns="adj_close")
)
ar.GreatTables(gt)
```
--------------------------------
### Configure In-House CDN for Arakawa Reports in Python
Source: https://ninoseki.github.io/arakawa/latest/reference/reports
This snippet shows how to configure an in-house CDN for Arakawa reports by setting the AR_CDN_BASE environment variable. This allows reports to load assets from a custom CDN instead of the default jsDelivr. It assumes you have a Python script named 'report.py'.
```python
AR_CDN_BASE=http://... python report.py
```
--------------------------------
### Create and Plot Map with Folium
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/plots
This snippet demonstrates initializing a Folium map centered on specific coordinates and then plotting data onto it using a hypothetical `ar.Plot` function. It requires the 'folium' library.
```python
import folium
m = folium.Map(location=[45.5236, -122.6750])
ar.Plot(m)
```
--------------------------------
### Report Saving and Stringifying
Source: https://ninoseki.github.io/arakawa/latest/reference/reports
This section covers the methods for saving and stringifying reports using the `Report` object.
```APIDOC
## POST /report/save
### Description
Save a report as an HTML file.
### Method
POST
### Endpoint
/report/save
### Parameters
#### Request Body
- **path** (str) - Required - A file path to store the document.
- **open** (bool) - Optional - Open in your browser after creating. Defaults to False.
- **name** (str | None) - Optional - A name of a report. Optional. Uses path if not provided. Defaults to None.
- **formatting** (Formatting | None) - Optional - Sets the basic app styling. Defaults to None.
- **cdn_base** (str | None) - Optional - Base URL of CDN. Defaults to None.
- **standalone** (bool) - Optional - Whether or not to inline assets in an HTML instead of loading via CDN or not. Defaults to False.
### Request Example
```json
{
"path": "report.html",
"open": false,
"name": null,
"formatting": null,
"cdn_base": null,
"standalone": false
}
```
### Response
#### Success Response (200)
- **message** (str) - Indicates successful save.
#### Response Example
```json
{
"message": "Report saved successfully to report.html"
}
```
## POST /report/stringify
### Description
Stringify a report as an HTML string.
### Method
POST
### Endpoint
/report/stringify
### Parameters
#### Request Body
- **name** (str | None) - Optional - A name of a report. Optional. Uses path if not provided. Defaults to None.
- **formatting** (Formatting | None) - Optional - Sets the basic app styling. Defaults to None.
- **cdn_base** (str | None) - Optional - Base URL of CDN. Defaults to None.
- **resizable** (bool) - Optional - Wether or not to allow make an iframed report resizable or not. Defaults to True.
- **standalone** (bool) - Optional - Whether or not to inline assets in an HTML instead of loading via CDN or not. Defaults to False.
### Request Example
```json
{
"name": null,
"formatting": null,
"cdn_base": null,
"resizable": true,
"standalone": false
}
```
### Response
#### Success Response (200)
- **html_string** (str) - The HTML representation of the report.
#### Response Example
```json
{
"html_string": "..."
}
```
```
--------------------------------
### Embed Image using Arakawa Media Block
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/embeds
This snippet demonstrates how to embed an image file into an Arakawa application. The `ar.Media` block displays the image inline and allows users to download it. Supported image formats depend on the browser. Parameters include `file` (path to image), `name`, `caption`, and `label`.
```python
ar.Media(file="./image.png", name="Image1", caption="Arakawa in action!")
```
--------------------------------
### Visualize Graph Data with Arakawa Sigma
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/network
Renders a graph directly from provided data using Sigma.js and Graphology. Requires node data with 'label' attributes and supports customizable layout settings. The 'data' parameter is a dictionary containing graph options, attributes, nodes, and edges.
```python
ar.Sigma(
data={
"options": {"type": "mixed", "multi": False, "allowSelfLoops": True},
"attributes": {},
"nodes": [
{
"key": "A",
"attributes": {
"label": "A",
"size": 20,
},
},
{"key": "B", "attributes": {"label": "B", "size": 20}},
],
"edges": [{"key": "geid_179_0", "source": "A", "target": "B"}],
}
)
```
--------------------------------
### Create Styled Table From DataFrame using ar.Table
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/data
Creates an HTML table from a pandas DataFrame that includes DataFrame Styles. This allows for custom formatting such as trend visualization, cell highlighting, or adding bar charts. It takes a styled pandas Styler object as input.
```python
import pandas as pd
import numpy as np
df = pd.DataFrame({"A": np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list("BCDE"))], axis=1)
ar.Table(df.style.background_gradient(cmap="viridis"))
```
--------------------------------
### Create PasswordField Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding a password type input field. It takes a single string argument for the input's name.
```python
ar.PasswordField("password")
```
--------------------------------
### Embed NetworkX Graph with Arakawa NetworkX
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/network
Embeds a NetworkX graph into the application, rendered using Sigma.js. It accepts a NetworkX graph object and allows configuration of layout settings and layout functions. Nodes in the NetworkX graph should have a 'label' attribute for visualization.
```python
import networkx as nx
G = nx.karate_club_graph()
for ix, node in enumerate(list(G.nodes())):
G.nodes[node]["label"] = str(ix)
G.nodes[node]["size"] = G.degree(node)
ar.NetworkX(
G,
layout_settings={
"outbound_attraction_distribution": True,
"barnes_hut_optimize": True,
"adjust_sizes": True,
"lin_log_mode": True,
},
)
```
--------------------------------
### Configure Notebook-to-Report Conversion with Opt-out Mode
Source: https://ninoseki.github.io/arakawa/latest/reports/jupyter-integration
Generates Arakawa Blocks from a notebook, with the option to only include specific cells. Setting `opt_out=False` requires cells to be tagged with `ar-include` to be part of the report, allowing for selective content inclusion.
```python
blocks = ar.Blocks.from_notebook(opt_out=False)
```
--------------------------------
### NumberBox Input with Python
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/numbers
The NumberBox component allows for the creation of a numerical input field within a form. It accepts various parameters to customize its behavior and appearance, including name, help text, initial value, label, and validation rules. The input is handled using Python.
```python
ar.NumberBox("number")
```
--------------------------------
### NetworkX Graph Visualization
Source: https://ninoseki.github.io/arakawa/latest/reference/display-blocks/network
The `NetworkX` component embeds NetworkX graphs rendered by Sigma.js. It allows specifying a custom layout function and layout settings.
```APIDOC
## NetworkX Graph Visualization
### Description
This component embeds a NetworkX graph, rendered using Sigma.js, into your application. You can configure the layout algorithm and its settings.
### Method
`ar.NetworkX(
graph: NXGraph,
width: int = 960,
height: int = 540,
layout_settings: LayoutSettings | None = None,
layout_function: Callable[[NXGraph], Any] | None = None,
name: str | None = None,
label: str | None = None
)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **graph** (NXGraph) - Required - An NetworkX graph to attach.
- **width** (int) - Optional - A width of the graph. Default: 960.
- **height** (int) - Optional - A height of the graph. Default: 540.
- **layout_settings** (LayoutSettings | None) - Optional - Settings for the ForceAtlas2 layout. See https://www.npmjs.com/package/graphology-layout-forceatlas2#settings (each key should be snake_cased). Default: None.
- **layout_function** (Callable[[NXGraph], Any] | None) - Optional - A layout function. Defaults to `spring_layout`. Default: None.
- **name** (str | None) - Optional - A unique name for the block to reference when adding text or embedding. Default: None.
- **label** (str | None) - Optional - A label used when displaying the block. Default: None.
### Request Example
```python
import networkx as nx
G = nx.karate_club_graph()
for ix, node in enumerate(list(G.nodes())):
G.nodes[node]["label"] = str(ix)
G.nodes[node]["size"] = G.degree(node)
ar.NetworkX(
G,
layout_settings={
"outbound_attraction_distribution": True,
"barnes_hut_optimize": True,
"adjust_sizes": True,
"lin_log_mode": True,
},
)
```
### Response
#### Success Response (200)
This component renders a visualization and does not return a JSON response.
#### Response Example
None
```
--------------------------------
### Create HiddenField Input
Source: https://ninoseki.github.io/arakawa/latest/reference/control-blocks/texts
Allows adding a hidden type input field. It requires a 'name' and an 'initial' value for the input.
```python
ar.HiddenField("hidden", initial="foo")
```