Skip to content

3. Your first chart

step3_first_bar_chart.py
from babel.support import NullTranslations
from polychromos.color import HSLColor
from tutorial_data import METADATA, SALES, run_query

from orama.strategies import BarChartStrategy
from orama.theme import Theme
from orama.variables import Aggregation

# 1. Describe the chart: *what* to group by and *what* to compute. No data is involved yet.
strategy = BarChartStrategy(
    fields_metadata=METADATA,
    category_variables=["country"],
    aggregation=Aggregation(name="total_revenue", function="sum", field="revenue"),
    title="Revenue by country",
)

# 2. Ask the strategy which queries it needs, and run them against your data.
print(strategy.get_query_params()["main"].group_fields)  # ['country']
dfs = run_query(strategy, SALES)

# 3. Build the figure. The theme supplies every color; a translations object localizes labels.
theme = Theme(
    colors={
        "background": HSLColor.from_hex("#ffffff"),
        "primary_color_normal": HSLColor.from_hex("#4c66aa"),
    }
)
view = strategy.build(dfs, NullTranslations(), theme)

view.figure.show()  # opens it in your browser; `view.to_html()` gives an HTML fragment instead

Run it, and a browser tab opens with:

Revenue by country

What just happened

  • Describe


    The strategy knows what to group (country) and what to compute (sum(revenue)), but holds no data.

  • Query


    get_query_params() returns the group-by fields, the aggregations and the expected result schema. You run them. Here run_query uses Polars; yours could be SQL.

  • Build


    build(dfs, tr, theme) returns a FigureView: the Plotly figure plus its caption, description and storytelling context.

build() or plot()?

Prefer build(). It does the same as plot() and also runs your callbacks.

What's in a FigureView

view.figure                 # the plotly.graph_objects.Figure
view.caption                # text for a <figcaption>, or None
view.to_html()              # an HTML fragment you can embed anywhere
view.figure.write_image(…)  # static images need the optional kaleido package

Why does Aggregation take a name?

It is the column the query must produce (total_revenue). The strategy reads that column back when it builds the figure, so the name only has to be unique within the chart.

Next: themes and colors →