Morph

Code Snippet / 選択フォームを使ってplotlyのChartの値をフィルタリングする

選択フォームを使ってplotlyのChartの値をフィルタリングする

SelectFormとPlotlyを使用してチャートの値をフィルタリングする方法

この例では、アメリカの人口データを使用して、チャートデータをフィルタリングする方法を説明します。以下のフィルタを適用します:

  • 日付でフィルタリングするための日付ピッカー
  • 州でフィルタリングするためのセレクトフォーム

Code

Python

import numpy as np
import pandas as pd
import plotly.express as px

import morph
from morph import MorphGlobalContext

@morph.func
def generate_population_data(context: MorphGlobalContext):
    # Initialize
    dates = pd.date_range(start="2022-01-01", end="2024-12-31", freq="M").strftime("%Y-%m-%d")
    states = ["California", "Texas", "Florida", "New York", "Illinois"]  # List of states

    # Generate dummy data
    data = pd.DataFrame({
        "date": np.tile(dates, len(states)),  # Repeat dates for all states
        "state": np.repeat(states, len(dates)),  # Repeat each state for all dates
        "population": np.random.randint(100000, 10000000, size=len(dates) * len(states))  # Generate random population data
    })
    return data

@morph.func
@morph.load_data("generate_population_data")
def filter_plotly_chart(context: MorphGlobalContext):
    data = context.data["generate_population_data"]
    start_date = context.vars["start_date"]
    end_date = context.vars["end_date"]
    state = context.vars["state"]

    # apply filter
    df = data[data["date"].between(start_date, end_date)]
    if state != "all":
        df = df[df["state"] == state]
    fig = px.bar(df, x="date", y="population", color="state", title="Population Over Time by State")
    return fig

SQL

{{
    config(
        name = "get_state_list"
    )
}}

select
    distinct state
from
    {{load_data("generate_population_data")}}

MDX

export const title = "Filter plotly chart"
export const dateRangeStart = variable("2024-01-01");
export const dateRangeEnd = variable("2024-09-30");
export const stateList = getJson({
    alias: 'get_state_list',
})
export const stateSelected = variable("all");

# Filter plotly chart

This example shows how to filter a plotly chart.

<div className="p-4 border border-gray-300 rounded-lg shadow-md">
    <Grid cols="2">
        <div>
            <DataTable
                loadData="generate_population_data"
            />
        </div>
        <div>
            <div className="flex items-center gap-3">
                <p>Date Range:</p>
                <div className="flex-1">
                    <VariableDatePicker
                        type="range"
                        variables={[
                            dateRangeStart,
                            dateRangeEnd
                        ]}
                    />
                </div>
            </div>
            <div className="flex items-center gap-3">
                <p>State:</p>
                <div className="flex-1">
                    <VariableSelect variable={stateSelected}>
                        <VariableSelectItem value="all">Not selected</VariableSelectItem>
                        <VariableSelectItems items={stateList} labelKey="state" valueKey="state" />
                    </VariableSelect>
                </div>
            </div>
            <Embed
                loadData="filter_plotly_chart"
                variables={{
                    start_date: dateRangeStart,
                    end_date: dateRangeEnd,
                    state: stateSelected
                }}
                height={400}
            />
        </div>
    </Grid>
</div>

Result

Filter plotly chart