Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make a grouped charts #191

Closed
1 task done
vmisusu opened this issue Dec 5, 2023 · 7 comments
Closed
1 task done

Make a grouped charts #191

vmisusu opened this issue Dec 5, 2023 · 7 comments
Assignees
Labels
General Question ❓ Issue contains a general question

Comments

@vmisusu
Copy link

vmisusu commented Dec 5, 2023

Question

Hi, how can i built grouped charts?

In example, i want to built a bar chart with not pure Price, i want to do it with Sum of Price or Mean of Price for this years which places at x-axis.

But in Selector i want to filter pure Dataframe for a prices in example (and after built grouped chart)

Code/Examples

df = df[["brand", "year", "price"]]

components=[
vm.Graph(
id="win_time_graph",
figure=px.bar(
data_frame = df,
x="year",
y="price",
color="brand",
),
),

---> i want to built MEAN of prices for every Year

Other information

No response

vizro version

last

Python version

3.11

OS

win 10

Code of Conduct

@vmisusu vmisusu added General Question ❓ Issue contains a general question Needs triage 🔍 Issue needs triaging labels Dec 5, 2023
@petar-qb
Copy link
Contributor

petar-qb commented Dec 5, 2023

Hi @vmisusu and thanks for the question.

If I understand you correctly, you need to create custom chart (adding some average values on the bar chart) with filtered data (data filtered by selected vm.Filter values). You can achieve it utilising custom charts feature described in the official Vizro documentation you can find here.

I also created additional example for you where I tried to configure something similar you probably need:

import pandas as pd
import numpy as np
import random

import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.models.types import capture

# Creating random data for demonstration
years = [random.choice([2018, 2019, 2020]) for _ in range(100)]
brand = [random.choice(["Brand A", "Brand B", "Brand C"]) for _ in range(100)]
prices = np.random.randint(10, 100, 100)  # Random prices for each row

# Creating a DataFrame
df = pd.DataFrame({'Brand': brand, 'Year': years, 'Price': prices})

@capture("graph")
def custom_graph(data_frame, x, y, color, barmode, title):
    """Custom graph function."""
    # This data_frame is filtered (with vm.Filter values from dashboard).
    # Other function arguments like: x, y, color, barmode, title are parametrised (with vm.Parameter values from dashboard)

    fig = px.bar(data_frame, x=x, y=y, color=color, barmode=barmode, title=title)
    # Do any customizations here

    # I added something the following code, but you're able to do any chart customisations you wany
    mean_price = data_frame.groupby(['Year', 'Brand']).mean().reset_index()
    for idx, brand in enumerate(["Brand A", "Brand B", "Brand C"]):
        fig.add_trace(
            px.scatter(
                mean_price,
                x=x, y=y, color=color, size=y
            )['data'][idx]
        )

    return fig


dashboard = vm.Dashboard(pages=[
    vm.Page(
        title="",
        components=[
            vm.Graph(
                id="graph_id",
                figure=custom_graph(
                    data_frame=df,
                    x='Year',
                    y='Price',
                    color='Brand',
                    barmode='group',
                    title='Price by Year and Brand'
                )
            )
        ],
        controls=[
            vm.Filter(
                column="Year",
                selector=vm.Dropdown(
                    options=[2018, 2019, 2020],
                    value=2018,
                )
            ),
        ]
    )
])

if __name__ == "__main__":
    Vizro().build(dashboard).run()

I hope the example and documentation will help you to find the answer.
Let us know if we can assist you more.

@petar-qb petar-qb self-assigned this Dec 6, 2023
@vmisusu
Copy link
Author

vmisusu commented Dec 7, 2023

Thank you very much, it works. Also, can you please tell me if Vizro supports Polars?

@petar-qb
Copy link
Contributor

petar-qb commented Dec 7, 2023

Glad to see it works. 🚀

Also, can you please tell me if Vizro supports Polars?

I guess you're asking for plotly polar charts integration with Vizro. By using "custom charts" Vizro feature with @capture("graph"), you can present any plotly chart in your dashboard (Filters and Prameters work for every plotly chart). 😄

Here is an example that shows how to achieve this. (it's pretty similar like you used to built MEAN of prices for every Year).

import random

import vizro.models as vm
import vizro.plotly.express as px
from vizro import Vizro
from vizro.models.types import capture


df = px.data.wind()


@capture("graph")
def custom_polar(data_frame, r, theta, color, line_close):
    """Custom graph function."""
    # This data_frame is filtered (with vm.Filter values from dashboard).
    # Other function arguments like: r, theta, color, line_close are parametrised (with vm.Parameter values from dashboard)

    fig = px.line_polar(
        data_frame,
        r=r,
        theta=theta,
        color=color,
        line_close=line_close,
        color_discrete_sequence=px.colors.sequential.Plasma_r
    )

    # Do any customizations here

    return fig


dashboard = vm.Dashboard(pages=[
    vm.Page(
        title="",
        components=[
            vm.Graph(
                id="graph_id",
                figure=custom_polar(
                    data_frame=df,
                    r="frequency",
                    theta="direction",
                    color="strength",
                    line_close=True,
                )
            )
        ],
        controls=[
            vm.Filter(column="strength"),
        ]
    )
])

if __name__ == "__main__":
    Vizro().build(dashboard).run()

More about custom charts in Vizro you can find on the link.

@vmisusu
Copy link
Author

vmisusu commented Dec 7, 2023

Hi, thank you, but im talking about Polars library. the speed would be several times faster if Vizro used Polars https://h2oai.github.io/db-benchmark/. also i suggest to use dash ag grid instead of datatable

@petar-qb
Copy link
Contributor

petar-qb commented Dec 7, 2023

Hi @vmisusu,

Hi, thank you, but im talking about Polars library. the speed would be several times faster if Vizro used Polars https://h2oai.github.io/db-benchmark/.

Thanks for the awesome suggestion, we really appreciate it. 🤩
I will get back to you with an answer as soon as we test this possibility.

also i suggest to use dash ag grid instead of datatable

We are currently working on supporting ag-grid natively in the Vizro.

How to make a custom DataTable (like a https://github.com/capture graph) ?

You can do it simply by decorating your function with the @capture("table"). More you can find here

@vmisusu
Copy link
Author

vmisusu commented Dec 7, 2023

Ty Petar, please consider supporting polars, I think it is necessary, given that the whole point of vizro is working with a dataframe in memory. Currently vizro cannot determine polars column names (detects them as [0,1,2,3,4...])

@antonymilne
Copy link
Contributor

Hi @vmisusu, sorry it took so long to respond to this point about polars because it's definitely a good one. I don't want it to get lost in this unrelated issue so I've opened a new issue and will respond there: #286.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
General Question ❓ Issue contains a general question
Projects
None yet
Development

No branches or pull requests

5 participants