CodeBlock Examples

This page demonstrates how to use CodeBlock elements in JSPlots to display Julia code with syntax highlighting and execute it to generate visualizations.

CodeBlocks are perfect for creating literate programming documents where you show both the code and its output.




Example 1: CodeBlock from a Function

Here we create a CodeBlock from a function that generates random stock data. The code is displayed with syntax highlighting, and we can execute it to get the data.




Julia
function generate_sample_data()
    n = 50
    x = 1:n
    y1 = cumsum(randn(rng, n)) .+ 100
    y2 = cumsum(randn(rng, n)) .+ 100

    return DataFrame(
        day = x,
        stock_a = y1,
        stock_b = y2,
        category = repeat(["Tech", "Finance"], inner=25)
    )
end
This function generates random walk stock price data



Stock Prices Over Time

Data generated by the code above

Plot Attributes


Data: df1




Example 2: Showing Code and Chart Together

This example shows how to display the code that creates a chart, alongside the chart itself.




Julia
function create_pie_chart()
    df = DataFrame(
        category = ["Product A", "Product B", "Product C", "Product D"],
        sales = [45000, 32000, 28000, 15000]
    )

    return PieChart(:sales_pie, df, :pie_data;
        label_cols = [:category],
        value_cols = [:sales],
        title = "Sales by Product"
    ), df
end
This function creates a pie chart showing sales by product



Sales by Product


Data: pie_data




Example 3: CodeBlock from a Code String

Sometimes you want to show code for educational purposes without executing it. Here's an example:




julia
# Tutorial: Creating a Simple Scatter Plot
using JSPlots, DataFrames, StableRNGs
rng = StableRNG(42)

# Step 1: Create your data
df = DataFrame(
    x = rand(rng, 100),
    y = rand(rng, 100),
    size = rand(rng, 100) .* 50,
    color = rand(rng, ["red", "blue", "green"], 100)
)

# Step 2: Create the scatter plot
scatter = ScatterPlot(:my_scatter, df, :my_data;
    x_cols = [:x],
    y_cols = [:y],
    size_col = :size,
    color_cols = [:color],
    title = "My First Scatter Plot"
)

# Step 3: Export to HTML
create_html(scatter, "output.html")
This code is for display only - not executed in this example



Example 4: Multi-Step Workflow

This example demonstrates how to show multiple code blocks that build on each other, creating a complete data analysis workflow.




Step 1: Prepare the Data




Julia
function prepare_analysis_data()
    dates = Date(2024,1,1):Day(1):Date(2024,1,31)
    df = DataFrame(
        date = dates,
        temperature = 15 .+ 10 .* sin.(2π .* (1:31) ./ 31) .+ randn(rng, 31) .* 2,
        humidity = 60 .+ 15 .* cos.(2π .* (1:31) ./ 31) .+ randn(rng, 31) .* 5,
        city = repeat(["New York", "Boston"], inner=16)[1:31]
    )
    return df
end
Generate synthetic weather data for analysis



Step 2: Visualize the Data




julia
# Create a line chart showing temperature trends
weather_chart = LineChart(:weather, weather_df, :weather_data;
    x_cols = [:date],
    y_cols = [:temperature, :humidity],
    title = "January Weather Patterns",
    notes = "Temperature (°C) and Humidity (%)"
)
Code to create the weather visualization



January Weather Patterns

Plot Attributes


Data: weather_data




Best Practices for Using CodeBlock

When to Use CodeBlock

CodeBlock Creation Methods

Method Syntax Executable?
From Function CodeBlock(my_function) ✓ Yes
From File CodeBlock("script.jl") ✓ Yes
From String CodeBlock(code_str, Val(:code)) ✗ No

Executing Code

For executable CodeBlocks, call them like functions using codeblock():

# Single return value
data = code_block()

# Multiple return values
chart, data = code_block()

# Alternative (but cb() is preferred)
data = execute_codeblock(code_block)
    

Tips




Summary

This page demonstrated CodeBlock features:

CodeBlocks make your analyses reproducible and educational by showing the code that generated every visualization!


This page was created using JSPlots.jl.