GithubHelp home page GithubHelp logo

mckinsey / vizro Goto Github PK

View Code? Open in Web Editor NEW
2.4K 17.0 100.0 85.83 MB

Vizro is a toolkit for creating modular data visualization applications.

Home Page: https://vizro.readthedocs.io/en/stable/

License: Apache License 2.0

Python 88.63% CSS 5.52% Jupyter Notebook 4.36% Shell 0.28% JavaScript 1.11% Jinja 0.09%
dashboard plotly plotly-dash python pydantic data-visualization visualization

vizro's Introduction



Vizro logo



Python version PyPI version License Documentation OpenSSF Best Practices


Visual Intelligence. Beautifully Engineered

Vizro is a toolkit for creating modular data visualization applications

What is Vizro?

Rapidly self-serve the assembly of customized dashboards in minutes - without the need for advanced coding or design experience - to create flexible and scalable, Python-enabled data visualization applications.

Use a few lines of simple configuration to create complex dashboards, which are automatically assembled using libraries such as Plotly and Dash, with inbuilt coding and design best practices.

Define high-level categories within the configuration, including:

  • Components: create charts, tables, input/output interfaces, and more.
  • Controls: create filters, parameter inputs, and custom action controllers.
  • Pages, layouts and navigation: create multiple pages, with customizable layouts and flexible navigation across them.
  • Actions and interactions: create interactions between charts, and use pre-defined or customized actions (such as exporting).

Configuration can be written in multiple formats including Pydantic models, JSON, YAML or Python dictionaries for added flexibility of implementation.

Optional high-code extensions enable almost infinite customization in a modular way, combining the best of low-code and high-code - for flexible and scalable, Python enabled data visualization applications.

Visit the "Why Vizro" section to see a more detailed explanation of Vizro use cases.

What is Vizro-AI?

vizro-ai is a separate package and extends Vizro to enable the use of natural language queries to build Plotly charts.

Gif to show vizro-ai

See the Vizro-AI documentation for more details.

Key benefits of Vizro



Live demo

You can see Vizro in action by clicking on the following image or by visiting vizro.mckinsey.com.

Examples

Installation and first steps

pip install vizro

See the installation guide for more information.

The get started documentation explains how to create your first dashboard.

Get hands on

See the how-to guides for step-by-step instructions on the key Vizro features.

Packages

This repository is a monorepo containing the following packages:

Folder Version Documentation
vizro-core PyPI version Vizro Docs
vizro-ai PyPI version Vizro-AI Docs

Community and development

We encourage you to ask and answer technical questions via the GitHub Issues. This is also the place where you can submit bug reports or request new features.

Want to contribute to Vizro?

The contribution guidelines explain how you can contribute to Vizro.

You can also view current and former contributors.

Want to report a security vulnerability?

See our security policy.

License

vizro is distributed under the terms of the Apache License 2.0

vizro's People

Contributors

anna-xiong avatar annmariew avatar antonymilne avatar axa99 avatar chiara-sophie avatar dependabot[bot] avatar github-actions[bot] avatar huong-li-nguyen avatar joseph-perkins avatar l0uden avatar lingyielia avatar maxschulz-col avatar nadijagraca avatar petar-qb avatar pre-commit-ci[bot] avatar stichbury avatar vizro-svc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vizro's Issues

App doesn't scale on mobile browsers

Description

First of all congratulations for the very good work! I wanted to try the demo you linked, but unfortunately the app page doesn't get scaled in mobile browsers. All you can see is the sidebar
Screenshot_20230926-201757

Expected behavior

The dashboard should be responsive and scale according to the screen size.

vizro version

Latest

Python version

OS

Android 12

How to Reproduce

  1. Open the demo on a mobile browser

Output

Screenshot_20230926-201757

Code of Conduct

Automatically generated navigation homepage

The Homepage on https://vizro.mckinsey.com/ is currently written entirely manually but follows a very clear formula. Following #176 we now have a field Page.description and so all of the ingredients are in place with the exception of the page image. Somehow we should make it possible to automatically generate such a homepage. In theory this sounds pretty easy to do.

Major considerations

  • What would be the right user API for it? A new HomePage model that subclasses Page? A Homepage model that includes a Page model? Just some Python helper functions? We'd like to follow our paradigm of extensibility and customisability and enable something that's possible from YAML too 🤔
  • How does this all relate to Navigation and different ways of grouping pages in hierarchy?

Minor considerations

  • How does page image fit into this? Should we change these to Google material icons? Do we want a Page.image field that's also used in meta tags (originally existed in #176 but removed)? Or to automatically pick up an image with filename page.id? Could we generate preview images of the pages automatically as discussed in final point of this comment and subsequent responses?

Non equal distribution of space when using cards

Question

When using a card and a graph on the same page, the space is distributed equally. What setting do you need to apply to make the card smaller.

Code/Examples

components=[
vm.Card(
text="""
### Card Title
text
"""
),

        vm.Graph(
            id="val_stocks",
            figure= code to get some figure
            ),
        ),

Other information

No response

vizro version

0.1.3

Python version

No response

OS

MacOs

Code of Conduct

How to modify card text based on a value selected in Dropdown filter?

Question

How can I modify the card text based on a value selected in a Dropdown filter?

For example below is how my basic Vizro app looks:

Screenshot from 2023-12-28 11-25-23
Screenshot from 2023-12-28 11-25-42

How can I target my CustomCard to change text when I select another value in my Merk brand filter?

Code/Examples

class CustomCard(vm.Card):
    type: Literal['custom_card'] = 'custom_card'

    def build(self):
        card_build_obj = super().build()
        # Overwrite default settings - card_build_obj[self.id] fetches the underlying dcc.Markdown
        card_build_obj[self.id].dangerously_allow_html = True
        card_build_obj[self.id].mathjax = True
        return card_build_obj
    

vm.Page.add_type("components", CustomCard)


@capture("graph")
def chart_daily_bundle_sales_brand(
    data_frame: pd.DataFrame, 
    x: PandasField = None, 
    y: PandasField = None, 
    title: ChartTitle = None
):
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=data_frame[x].dt.date,
            y=data_frame[y],
            mode="lines",
            name="Absolute aantal",
        )
    )
    fig.update_layout(title=title, title_x=0.25, hovermode="x unified", legend=dict(x=0, y=1.1, traceorder="normal", orientation="h"))
    fig.update_xaxes(type="category", tickangle=55)
    return fig


@capture("graph")
def chart_daily_bts_ratios_brand(
    data_frame: pd.DataFrame,
    x: PandasField = None,
    y: PandasField = None,
    title: ChartTitle = None
):
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=data_frame[x].dt.date,
            y=data_frame[y],
            mode="lines",
            name="Merk bundle-to-single verhouding"
        )
    )
    fig.update_layout(title=title, title_x=0.25, yaxis_title="%", hovermode="x unified", showlegend=False)
    fig.update_xaxes(type="category", tickangle=55)
    return fig


page_brand = vm.Page(
    title="Merk",
    layout=vm.Layout(
        grid=[
            [0, 1, 2, 3],
            [4, 4, 4, 4],
            [5, 5, 5, 5],
            [6, 6, 6, 6],
        ],
        row_min_height="200px"
    ),
    components=[
        CustomCard(
            text=f"""
                #### Dagelijkse virtuele bundel sales

                Gemiddelde groei in sales 2 maanden vóór en ná de kortingsverhoging:

                **Absoluut** (voor): {mean_virtual_bundle_sales_pre_discount_change}<br>
                **Absoluut** (na): {mean_virtual_bundle_sales_post_post_discount_change}<br>
            """
        ),
        CustomCard(
            text=f"""
                #### Dagelijkse harde bundel sales

                Gemiddelde groei in sales 2 maanden vóór en ná de kortingsverhoging:

                **Absoluut** (voor): {mean_hard_bundle_sales_pre_discount_change}<br>
                **Absoluut** (na): {mean_hard_bundle_sales_post_discount_change}<br>
            """
        ),
        CustomCard(
            text=f"""
                #### Dagelijkse bundel-to-single ratio

                Gemiddelde bundel-to-single ratio 2 maanden vóór en ná de kortingsverhoging:

                **Voor**: {mean_bts_ratio_pre_discount_change}%<br>
                **Na**: {mean_bts_ratio_post_discount_change}%
            """
        ),
        CustomCard(
            text="""
                #### Correctie

                Kortingsverhoging: **2023-10-17**<br>
                Black Friday: **2023-11-17** t/m **11-27** <br>(verwijderd om bias te mijden)
            """
        ),
        vm.Graph(
            id="daily_virtual_bundle_sales_brand",
            figure=chart_daily_bundle_sales_brand(
                ts_daily_vh_bundle_sales_brand_df, 
                x="date", 
                y="quantity_virtual_bundles",
                title="Sold <b>virtual</b> bundles"
            )
        ),
        vm.Graph(
            id="daily_hard_bundle_sales_brand",
            figure=chart_daily_bundle_sales_brand(
                ts_daily_vh_bundle_sales_brand_df, 
                x="date", 
                y="quantity_hard_bundles",
                title="Sold <b>hard</b> bundles 2"
            )
        ),
        vm.Graph(
            id="daily_bts_ratios_brand",
            figure=chart_daily_bts_ratios_brand(
                ts_daily_vh_bundle_sales_brand_df, 
                x="date", 
                y="bts_ratio",
                title="Bundel-to-single ratio",
            )
        ),
    ],
    controls=[
        vm.Filter(column="discount_change", selector=vm.Dropdown(title="Discount change")), 
        vm.Filter(column="brand", selector=vm.Dropdown(title="Merk")),
    ]
)

Other information

No response

vizro version

0.1.7

Python version

3.10

OS

Linux

Code of Conduct

The graph sample from the doc doesn't work

Description

The vm.Graph sample doesn't work:
https://vizro.readthedocs.io/en/stable/pages/user_guides/graph/

Expected behavior

No response

vizro version

0.1.7

Python version

3.11.5

OS

Mac OS Sonoma 14.2

How to Reproduce

Copy the sample to app.py and run
python app.py

Output

It returns this error message:
AttributeError: 'DataFrame' object has no attribute 'iteritems'

(might be due to pandas version 2.0.3?)

Code of Conduct

Consider AG Grid as recommended default over Dash data table

Originally posted by @antonymilne in #114 (comment)

Just from quickly playing around with the the example dashboard here, I prefer the AG Grid. I wonder whether we should be recommending that instead of Dash data table as the default table for people to use in the (I guess) most common case that someone just wants to draw a nice table?

  • for small screen sizes the table has its own little scroll bar rather than stretching out the whole screen
  • I can rearrange column order by drag and drop
  • the active row is highlighted
  • the style just feels a bit more modern and slicker somehow (though dark theme is obviously not usable right now)

I'd guess some of these you can probably also achieve with Dash data table by using appropriate styling parameters or arguments though?

These are just my impressions from playing around for a few seconds though, so don't take them too seriously - it's the first time I've used both sorts of table, so I don't know what each is capable of or how easily we can get all the features we want out of each. But curious what other people think - should Dash data table or AG Grid be the "default" table that we suggest people to use?

Work out what to do with example apps

More generally though I think we're getting to the point where we need to figure out what the default/app.py is for, since we have a few different things we're interested in:

  1. Trying out features while we develop stuff like you do here
  2. The nice gapminder example
  3. The public demo
  4. A showcase of all the different components

At the moment these are all served by the same default/app.py but that's probably not good in the longer term and we need some new example dashboards which have different responsibilities. We should also re-consider whether we want the yaml/json/dict versions and what they should contain.

Originally posted by @antonymilne in #114 (comment)

Rerun Vizro Dashboard in Jupyter doesn't work

Description

ValidationError: 1 validation error for Graph
figure
Component with id=scatter_chart already exists and is mapped to dataset 140638475834896. Components must uniquely map to a dataset across the whole dashboard. If you are working from a Jupyter Notebook, please either restart the kernel, or use 'from vizro.managers import data_manager; data_manager._reset()`. (type=value_error)

'from vizro.managers import data_manager; data_manager._reset()`. After I follow the instruction and rerun the cell, I run into a new error.

DuplicateIDError: Model with id=scatter_chart already exists. Models must have a unique id across the whole dashboard. If you are working from a Jupyter Notebook, please either restart the kernel, or use 'from vizro.managers import model_manager; model_manager._reset()`.

After I run 'from vizro.managers import model_manager; model_manager._reset()`, no error is raised but it doesn't show the dashboard UI anymore.

image

Expected behavior

I expect the dashboard render properly. Workaround is restart the Kernel which work fine but is considerably slower.

vizro version

0.1.4

Python version

3.8.5

OS

MacOS

How to Reproduce

Follow the tutorial and run it in a notebook twice.

https://vizro.readthedocs.io/en/stable/pages/tutorials/first_dashboard/#4-explore-further

Output

No response

Code of Conduct

How to create user for vizro toolkit dashboard

Question

How to create login user for vizro toolkit dashboard?

Code/Examples

No response

Other information

No response

Which package?

vizro

Package version

No response

Python version

python3.8

OS

ubuntu

Code of Conduct

Can we add a live update feature?

What's the problem this feature will solve?

I find this tool very easy to use but what I want is add a refresh icon or update each second to get the real time data to monitor the resource usuage.

Describe the solution you'd like

when get the data from data source, i.e. call a function, refresh the data every second.

Alternative Solutions

None

Additional context

None

Code of Conduct

Potential ways forward regarding a smoother experience in Jupyter

At the moment, using Vizro in a Jupyter notebook may feel annoying when re-evaluating cells, because

  • adding a new model with the same ID causes the an error.
  • in addition, there is a further issue, that currently every instantiation of a model without ID adds it newly to the model_manager (MM), thus creating a situation where models are in the MM that are not used within the dashboard

Solving this may entail multiple levels of investigation/considerations. See also #56 for some notes and code around this issue.

Short term solution
In the short term, #59 ensures that users get a more comprehensive error message when working in Jupyter.

Note that this does not catch all cases, as a cell could also not contain a model with manual ID, thus never triggering an error that catches the additional models added to the MM.

Medium term solution

  • remove the restrictions to add duplicate ID's but at the same time improve all reference to the MM, especially _items_with_type
  • _items_with_type in particular should not be a wild card search to any type, but if at all search for a Dashboard, all subsequent scans should be hierarchical and on a per need basis
  • likely further investigation about consequences needed
  • note also: removing the duplicate ID restriction can also cause confusion when users do NOT want to update a model, but by mistake copied one

Long term solution

Idea 1

  • go back to hierarchical registering approach (ie not register upon instantiation)

Reasoning from @antonymilne as to why this is NOT a no-brainer:

I think this is one of the disadvantages of the recursive approach to registering models in the model manager. Let’s say you go for the recursive approach like this:

  1. call dashboard.register that recursively registers all models
  2. pre_build uses models existing in model manager
  3. pre_build can itself create models
  4. if we want those models to also be registered in the model manager then we need to somehow register them e.g. by manually calling selector.register or by re-running dashboard.register after the pre-build

This step 4 with the extra manual registration stage is a bit ugly, annoying and easy to forget, whereas if it’s done automatically upon model instantiation it’s not required at all.
tbh the current solution with pre_build creating models is also not very satisfactory, as described in the comment:

  # Note that a pre_build method can itself add a model (e.g. an Action) to the model manager, and so we need to
  # iterate through set(model_manager) rather than model_manager itself or we loop through something that
  # changes size.
  # Any models that are created during the pre-build process *will not* themselves have pre_build run on them.
  # In future may add a second pre_build loop after the first one. 

Overall if we do want to change how components are registered in the model manager then we’d need to think about it in combination with pre_build. Hopefully there’s some better overall solution, but I don’t think we can change one without thinking about the other at the same time. I’d love if we could come up with an improvement here, but I don’t think there’s going to be an easy solution.

Idea 2

  • introduce some form of context_manager that associates every model with a dashboard

Idea 3

  • introduce a flag when overriding is allowed

Add favicon to vizro docs

This is partly a learning exercise for me as I've not used mkdocs before, but also because it would be nice to start to use the Vizro branding across our content where possible. The goal is to set up the favicon to enhance the docs beyond the standard logo, which seems relatively straightforward.

Work out what to do with registering pages and model manager

Rough notes for now... A few somewhat related problems:

Authentication/authorization support or documentation

What's the problem this feature will solve?

Typically, organizations need to control access to data dashboards to ensure only trusted stakeholders can view the information.

Describe the solution you'd like

Authentication and authorization are the mechanisms most commonly used to provide access control. It is possible to leverage an existing authentication framework in the Python ecosystem and build an authorization mechanism for per-dashboard, chart, and query/data source control (depending on the desired granularity).

Alternative Solutions

VPN is an alternative but is typically less user-friendly while still leaving the possibility of accidentally exposing dashboards on public-facing URLs.

Additional context

Plotly Dash enterprise demonstrates the need for authentication/authorization. The package django-plotly-dash shows one example of integrating Plotly Dash in a framework with inbuilt authentication/authorization mechanisms.

Code of Conduct

Replace all `html.P()` with `html.Label()` in all form components

Question

Context why this is beneficial: https://teamtreehouse.com/community/labels-vs-paragraphs#:~:text=The%20tag%20is%20just,in%20the%20CSS.

Code/Examples

Replace html.P(self.title) with html.Label(self.title) for all form components (dropdown, checklist, etc.) and where applicable

Other information

No response

Which package?

vizro

Package version

0.1.9

Python version

3.9

OS

No response

Code of Conduct

BUG: `value` for slider does not work properly

The below example does not set the slider default (3) properly. It seems that the custom action on_page_load fetches the minimum.

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


@capture("graph")
def scatter_with_line(data_frame, x, y, color=None, size=None, hline=None):
    fig = px.scatter(data_frame=data_frame, x=x, y=y, color=color, size=size)
    fig.add_hline(y=hline, line_color="gray")
    return fig


page_0 = vm.Page(
    title="Custom chart",
    components=[
        vm.Graph(
            id="enhanced_scatter",
            figure=scatter_with_line(
                x="sepal_length",
                y="sepal_width",
                color="species",
                size="petal_width",
                hline=3,
                data_frame=px.data.iris(),
            ),
        ),
    ],
    controls=[
        vm.Parameter( 
            targets=["enhanced_scatter.hline"],
            selector=vm.Slider(min=2, max=5, step=1, value=3, title="Horizontal line"),
        ),
    ],
)
dashboard = vm.Dashboard(pages=[page_0])

Vizro().build(dashboard).run()

Editable data table

Question

Is there a vizro component that allows the edition of a data table?
Or would it be possible (easy) to create such a component?

Code/Examples

No response

Other information

I would like to write a small app based on two small tables.
The user would need to fill in this table.

vizro version

0.1.7

Python version

3.11.5

OS

macOS-14.2-arm64-arm-64bit

Code of Conduct

No validation for Card.href can break page opening

Description

If we create path="/page page" for any page it will be available in browser like /page-page.
At the same time if we create Card.href="/page page" we'll get 404 during page opening.

Looks like to synchronise this values we should apply same validation for href and path

Expected behavior

No response

Which package?

vizro

Package version

0.1.8

Python version

3.9

OS

Mac OS

How to Reproduce

  1. Create one page with path="/page page"
  2. Create second page with Card.href="/page page"
  3. Run the dashboard and click Card on the second page.

Output

No response

Code of Conduct

A date filter

What's the problem this feature will solve?

I'd like to have a date filter, so I can filter to a certain date range.

Describe the solution you'd like

I'd expect a "Start date" and "End date" filter to show up.

Alternative Solutions

In our case, we only need to filter per month, so I can create a dropdown to filter to a certain month. However that is not very flexible.

Additional context

In our case we've got a MongoDB and I use pymongo to retrieve the data, which converts date values to date objects.

Code of Conduct

Optimise windows integration tests

Important

All the below is based on some very quick glancing through of recently run Actions. Before making any changes we should look properly at how long these jobs take and which jobs seem redundant.

I want our CI to remain super fast and slick. At the moment it's not too bad but there are several things I think could be optimised.

Let's start with the most blatant offender and probably easiest to fix, which seems to be windows integration tests. Very roughly it looks like these can take 6-8 mins when all other jobs take a maximum of 3 mins.

Currently we run integration tests on the following matrix:

os: [ubuntu-latest, windows-latest]
python-version: ["3.8", "3.9", "3.10", "3.11"]

Things to ponder:

  • can we speed these Windows tests up significantly?
  • if not, do we actually want to run it on every commit in every PR? (probably not I think)

Probably it's not really worthwhile covering all versions of Python on Windows but since they seem to be run in parallel, the actual number of jobs doesn't make a big difference I think, just the speed of each one.

Research and execute on docs to address plotly FAQs

We routinely tackle questions about plotly and it would be useful to have some standard answers (e.g. FAQs) or a document that guides readers. We may also be able to better link through to plotly docs in our content.

Task

  1. Make a list of common queries and answer these as standard FAQ. This may go into docs or maybe just as a pinned post on our (internal) slack channel or elsewhere (e.g. in our repo).

  2. Investigate plotly docs and see if we can better build on them to help our users understand their content.

  3. Extension task: Research if there is any scope for a contribution back to plotly e.g. if we spot a way to improve their docs nav/discoverability?

Add vertical/horizontal line to a px.line figure

What's the problem this feature will solve?

Enable developers to portray the significance behind a particular x (or y) value

Describe the solution you'd like

A simple mechanism for a developer to add a vertical (or horizontal) line to a given px.line figure. Please see the green line in the screenshot as an example of the expected output.

Screenshot 2023-10-07 at 12 17 11 AM

Alternative Solutions

I attempted multiple different parameter configurations of the fig.add_vline function as indicated in the plotly docs

    my_figure = px.line(
                    df_gapminder,
                    x="year",
                    y="gdpPercap",
                    color="data",
                    labels={"year": "Year", "data": "Data", "gdpPercap": "GDP per capita"},
                    color_discrete_map={"Country": "#afe7f9", "Continent": "#003875"},
                    markers=True,
                )
    
    my_figure.add_vline(1970)
    # my_figure.add_vline(x=1970)
    # my_figure.add_vline(x=1970, line_width=3)
    # my_figure.add_vline(x=1970, line_width=3, line_dash="dash")
    # my_figure.add_vline(x=1970, line_width=3, line_dash="dash", line_color="green")

Additional context

As noted in the docs, this appears to be a feature implemented by plotly. I'm curious if:

  1. This works on other people's machines - in which case it is an issue with my local MacOS
  2. OR If this feature is currently supported through another mechanism
  3. OR Suggestions on where to to start in order to support this feature

Code of Conduct

Getting FieldInfo error while running vizro

Description

Installed vizro using the mentioned steps.
When ran a simple program of getting vizro version , it ended up in below error

AttributeError Traceback (most recent call last)

  7 from vizro_ai.chains import ModelConstructor
  8 from vizro_ai.chains._llm_models import LLM_MODELS

----> 9 from vizro_ai.components import (
10 GetChartSelection,
11 GetCodeExplanation,
12 GetCustomChart,
13 GetDataFrameCraft,
14 GetDebugger,
15 GetVisualCode,
16 )
17 from vizro_ai.utils import _safeguard_check
...
---> 35 if field and field.field_info.description:
36 prop["description"] = field.field_info.description.split("\n")[0]
37 else:

AttributeError: 'FieldInfo' object has no attribute 'field_info'

Please can you help here.

Expected behavior

It should have outputted the version

vizro version

0.1.0

Python version

3.11.4

OS

Windows

How to Reproduce

Install package using pip install vizro_ai
Run the below program
from vizro_ai import VizroAI

print(VizroAI.version)

Output

No response

Code of Conduct

Rename docs pages that include `_` to use `-`

Google doesn't recognise underscores as word separators when it indexes pages. So if we have a page called first_dashboard then Google will report that as firstdashboard to its algorithm. (If we had first-dashboard then it would go into the mix as first dashboard which earns more google juice for the keywords "dashboard"). More explanation here

As we are at an early stage with Vizro, we can make some changes (and use RTD redirects to ensure we don't break anyone's links) that set the docs up for success later. SEO doesn't seem that important but every little helps.

Solution

  1. Rename pages
  2. Set up redirects in readthedocs to redirect to newly hyphenated pages for external users who have bookmarks, and blog posts we can't update etc.
  3. Change all existing internal linking within the docs to the new page names

Add Python 3.12 to tests

Quick and easy - do for both vizro-core and vizro-ai:

  • In our matrix on Github actions, we currently test on python-version up to and including 3.11. Let's add 3.12 to the list
  • Include 3.12 in classifiers in pyproject.toml
  • Include 3.12 in our badge in the README
  • Include 3.12 in [[envs.all.matrix]]
  • Make sure the relevant 3.12 jobs are required for merging in Github branch protection settings

Could be difficult but I don't expect it will be necessary, at least for vizro-core:

  • Fix any problems that make our code incompatible with 3.12

Convert warnings into errors in tests

Currently our tests show any deprecation warnings raised during running but these are easy to miss and I expect everyone ignores them (I do anyway). Let's get stricter about this so (a) we don't miss future deprecations in our dependencies that could break us and (b) our users aren't bothered by deprecation warnings.

This applies to both vizro-ai and vizro-core, though could be done in two separate PRs if easier.

  • Add filterwarnings = "error" to tool.pytest.ini_options in pyproject.toml
  • Run all tests and see what new errors are raised
  • Go through these errors and work out whether we should fix them or ignore them
  • For any that should be ignored, ignore them in the "least global" way possible.

See https://docs.pytest.org/en/7.1.x/how-to/capture-warnings.html for more guidance.

Updating Meta Tags

What's the problem this feature will solve?

One of the cool features of Dash Pages is that it’s easy to update the meta tags for each page. This is good for SEO and creating nice looking preview cards when sharing a link on social media.

Currently with the Vizro demo app, only the title is included in the meta tags. Here's what the link preview looks like:
vizro_on_forum

However, Dash Pages will update the meta tags with an image and description if supplied. For example, see the Dash Example Index. It has over 100 pages, each with it's own title, description and image:

vizro_vs_dash_example_index

Describe the solution you'd like

It's easy to enable this feature in Vizro. Simple include (an optional) description, image, and image_url parameter in the Page.

I could do a pull request if you would like this feature enabled. I got it working locally. You can't see what the link looks like until the app is deployed , but when inspecting the browser, you can see that the meta tags now include an image and description.

vizro_updated_meta

Alternative Solutions

No

Additional context

None at this time.

Code of Conduct

Uploading files in Vizro apps

Which package?

vizro

What's the problem this feature will solve?

Perhaps there is a way already to do it, but I want the user to be able to select a file on the local computer and use it for analysis. I was hoping that there was a "vizro" object to do uploads, but I can't find one. Lacking that, can one somehow include a dcc object, such as Upload, into a "vizro" app? I saw one place that said one vizro object was "a thin wrapper" on a dcc object, but I don't know if there is someway for me to do that. Also lacking that, could I make a multipage app where I could have a dcc Update on a separate page or perhaps as a dropdown? If not, I think you really should have an "Upload" object or some object that includes that functionality.

Describe the solution you'd like

I described ideally want to do Upload in a vizro object in the "What's the problem" section above.

Alternative Solutions

I described alternative solutions in the "What's the problem" section above.

Additional context

Is there a vizro forum for discussing this sort of issue? I looked at the "dash" forum, but it only seemed to mention vizro in one post.

Code of Conduct

Make a grouped charts

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

Have a component like Plotly Textarea to get text input from the user.

What's the problem this feature will solve?

Enabling users to input SQL queries for data retrieval can significantly enhance the utility of data connectors. This feature would allow for the generation of dynamic dashboards that can be customized according to user-defined queries as texts.

Describe the solution you'd like

The following functionality from https://dash.plotly.com/dash-core-components/textarea#textarea-properties will suit text-based input.

from dash import Dash, dcc, html, Input, Output, callback
app = Dash(__name__)
app.layout = html.Div([
  dcc.Textarea(
      id='textarea-example',
      value='Textarea content initialized\nwith multiple lines of text',
      style={'width': '100%', 'height': 300},
     ),
  html.Div(id='textarea-example-output', style={'whiteSpace': 'pre-line'})
 ])

@callback(
  Output('textarea-example-output', 'children'),
  Input('textarea-example', 'value')
 )
def update_output(value):
    return 'You have entered: \n{}'.format(value)

Alternative Solutions

A different approach would be to have dropdown menus where the user could select the list of tables and filters and we generate the query in the backend.

Additional context

I was thinking of implementing a component like the following. I haven't tested it yet, but will work on such a solution.

from typing import Optional
from dash import ClientsideFunction, Input, Output, State, clientside_callback, dcc, html
from pydantic import Field, validator

from vizro.models import Action, VizroBaseModel
from vizro.models._action._actions_chain import _action_validator_factory
from vizro.models._models_utils import _log_call

class Textarea(VizroBaseModel):
    """Textarea component for Vizro.

  Can be provided to [`Filter`][vizro.models.Filter] or
  [`Parameter`][vizro.models.Parameter]. Based on the underlying
  [`dcc.Textarea`](https://dash.plotly.com/dash-core-components/textarea).

  Args:
      value (Optional[str]): Default value for textarea. Defaults to `None`.
      title (Optional[str]): Title to be displayed. Defaults to `None`.
      actions (List[Action]): See [`Action`][vizro.models.Action]. Defaults to `[]`.
  """

  value: Optional[str] = Field(None, description="Default value for textarea.")
  title: Optional[str] = Field(None, description="Title to be displayed.")
  actions: List[Action] = []

  # Validator for actions, if needed
  _set_actions = _action_validator_factory("value")

  @_log_call
  def build(self):
      output = [Output(f"{self.id}_output", "children")]
      inputs = [Input(f"{self.id}_textarea", "value")]

      clientside_callback(
          ClientsideFunction(namespace="clientside", function_name="update_textarea_output"),
          output=output,
          inputs=inputs,
      )

      return html.Div(
          [
              html.P(self.title) if self.title else None,
              dcc.Textarea(
                  id=f"{self.id}_textarea",
                  value=self.value,
                  style={'width': '100%', 'height': 300},
              ),
              html.Div(
                  id=f"{self.id}_output",
                  style={'whiteSpace': 'pre-line'}
              ),
          ],
          className="textarea_container",
          id=f"{self.id}_outer",
      )

Code of Conduct

the selector option is from another selector

Question

I'd like to dynamic change the selector options according to the another selector.
for example:
I use titanic_data to set dropdown list:
first dropdown is pclass , it's including 1,2,3
second dropdown is deck it's including A,B,C,D,E,F,G
What I want is when select plass=2 on the first dropdown, the second dropdown only show D,E,F
because there are only deck D,E,F on pclass=2
This function can be done by callback in dash/plotly.
How can I achieve this function inVizro? Please advise, thank you!
image

Code/Examples

No response

Other information

No response

vizro version

No response

Python version

No response

OS

No response

Code of Conduct

Should vizro support polars (or other dataframes besides pandas)?

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...])

Originally posted by @vmisusu in #191 (comment)


I'm opening this issue to see whether other people have the same question so we can figure out what priority it should be. Just hit 👍 if it's something you'd like to see in vizro and feel free to leave and comments.

The current situation (25 January 2024) is:

  • vizro currently only supports pandas DataFrames, but supporting others like polars a great idea and something we did consider before. The main blocker previously was that plotly didn't support polars, but as of 5.15 it supports not just polars but actually any dataframe with a to_pandas method, and as of 5.16 it supports dataframes that follow the dataframe interchange protocol (which is now pip installable)
  • on vizro we could follow a similar sort of pattern to plotly's development1. Ideally supporting the dataframe interchange protocol is the "right" way to do this, but we should work out exactly how much performance improvement polars users would actually get in practice to see what the value of this would be over a simple to_pandas call. The biggest changes we'd need to make would be to actions code like filtering functionality (FYI @petar-qb). I don't think it would be too hard, but it's certainly not a small task either

FYI @astrojuanlu

Footnotes

  1. https://github.com/plotly/plotly.py/pull/4244 https://github.com/plotly/plotly.py/pull/4272/files https://github.com/plotly/plotly.py/pull/3901 https://github.com/plotly/plotly.py/issues/3637

Using multiple datasets for custom graphs

Question

Is it possible to use multiple datasets for custom graphs? Right now, you have to create a function with @capture and data_frame as an argument, but what, if I want to use two datasets so it can also play nicely with the filter from vizro.

Code/Examples

No response

Other information

No response

vizro version

No response

Python version

No response

OS

No response

Code of Conduct

Ability to create control headers with horizontal rulers

What's the problem this feature will solve?

@maxchristlmck raised that he would like to have the ability to create grouping headers for the controls with a horizontal ruler in place, see this draft PR: #81

Describe the solution you'd like

Ability to add control headers and horizontal rulers

Alternative Solutions

Additional context

Code of Conduct

How to deploy a Vizro app to Heroku?

Question

Could you provide an example on how the main.py or app.py should look like

In a Dash app , you typically have

app= Dash ( name)
server=app.server

if name == "main":
........

How is it supposed to work for Vizro?

Code/Examples

My current code :
app = Dash(name)
server = app.server

if name == "main":
app = Vizro().build(create_dashboard()).run( debug=True). --> where create_dashboard create the most of the code to create the layout.

doesn't run
I get : dash.exceptions.NoLayoutException: The layout was None at the time that run_server was called.

Other information

No response

vizro version

0.1.5

Python version

3.9.18

OS

MacOS

Code of Conduct

Sliders doesn't work with big numbers

Description

If you configure sliders with big numbers and change it using input field you'll get an error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside
componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent 
infinite loops.
image

Expected behavior

No response

vizro version

0.1.7

Python version

3.9

OS

Mac

How to Reproduce

  1. Use gapminder dataset
  2. Configure range_slider like this: RangeSlider(step=1000000.0, min=1000000, max=10000000) for pop column
  3. Try to change slider value inside using input form

Output

No response

Code of Conduct

Absence of openpyxl library causes console errors

Description

When trying to export xlsx file using actions, console error occurs

Traceback (most recent call last):
  File "/Users/o/PycharmProjects/vizro/vizro-core/src/vizro/models/_action/_action.py", line 80, in callback_wrapper
    return_value = self.function(**inputs) or {}
  File "/Users/o/PycharmProjects/vizro/vizro-core/src/vizro/models/types.py", line 59, in __call__
    return self.__function(**bound_arguments.arguments)
  File "/Users/o/PycharmProjects/vizro/vizro-core/src/vizro/actions/export_data_action.py", line 61, in export_data
    callback_outputs[f"download-dataframe_{target_id}"] = dcc.send_data_frame(
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/dash/dcc/express.py", line 91, in send_data_frame
    return _data_frame_senders[name](writer, filename, type, **kwargs)
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/dash/dcc/express.py", line 32, in send_bytes
    content = src if isinstance(src, bytes) else _io_to_str(io.BytesIO(), src, **kwargs)
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/dash/dcc/express.py", line 58, in _io_to_str
    writer(data_io, **kwargs)
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/pandas/core/generic.py", line 2252, in to_excel
    formatter.write(
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 934, in write
    writer = ExcelWriter(  # type: ignore[abstract]
  File "/Users/o/anaconda3/envs/w3af/lib/python3.8/site-packages/pandas/io/excel/_openpyxl.py", line 56, in __init__
    from openpyxl.workbook import Workbook
ModuleNotFoundError: No module named 'openpyxl'

Expected behavior

No response

vizro version

0.1.3

Python version

3.8

OS

Mac OS

How to Reproduce

  1. Install vizro package into clean env
  2. Add export xlsx action to the dashboard
  3. Run export action

Output

No response

Code of Conduct

Use vizro.models.button to switch to another page

Question

Hi there!

As far as I know, the only way to create a clicktable container/button to switch to another Page is to use a Card, and use the href parameter.

I was wondering if this was possible to do the same thing using Button instead of Card ? The Button design seems a bit more user-friendly. At the moment, Button needs to take an action as an input, but the only two actions available are filter actions, or data exports, so I haven't found a way to do this.

Thank you!

Code/Examples

No response

Other information

No response

vizro version

No response

Python version

No response

OS

No response

Code of Conduct

Add direct feature-by-feature comparisons with `streamlit` and `dash` to documentation

What's the problem this feature will solve?

My first question when I saw vizro release note and docs was: "How is it different from streamlit and dash"?

I asked this question on slack, and thanks for the reply! Though I clearly see that many other users are asking for exactly the same thing. So that is probably a good sign that there should be a separate dedicated page in the docs elaborating on this particular comparison.

This would allow users to understand when to choose vizro over the other two mentioned framework, and in general advertise the product.

Describe the solution you'd like

The best reference that comes to mind is this comparison of neptune with mlflow.

  • Probably to start, even a small table or couple of paragraphs of comparison would be enough.
  • Long term, I'd love to see the feature-by-feature comparison just like on that page I reference - if you scroll down you'll be able to expand a huge table with like 50 parameters.

Alternative Solutions

Another example is... kedro-mlflow plugin docs that compare kedro with mlflow.

Additional context

Hopefully that helps, and I believe that this addition to documentation helps vizro grow.

Code of Conduct

Allow Parameters to have optional selection

What's the problem this feature will solve?

Currently when using parameters it is impossible to use None as this is forbidden by pydantic types

Describe the solution you'd like

Ability to allow parameters to take None as value

Alternative Solutions

Pydantic validation forbids any feasible work arounds

Additional context

None required

Code of Conduct

How to add color to text in Markdown with vm.Card?

Question

I have some markdown text that I would like to have be colored red/green (percentual growth). How to accomplish this with vm.Card?

Code/Examples

components=[
        vm.Card(
            text=f"""
                #### Dagelijkse virtuele bundel sales

                Gemiddelde groei in sales 2 maanden vóór en ná de kortingsverhoging:

                Absoluut (voor): 709 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Absoluut (na): 710

                Gecorrigeerd (voor): 709 &nbsp;&nbsp;&nbsp;&nbsp; Gecorrigeerd (na): 710 <p style="color: green">(+1.5%)</p>
            """
        ),
       ...

Other information

For example, it's not possible right now to add HTML in the Markdown, eg: <p style="color: green">(+1.5%)</p>

vizro version

0.1.7

Python version

3.10

OS

Ubuntu 22.04

Code of Conduct

Use datasets from data_manager for custom plots of plotly.graph_objects

What's the problem this feature will solve?

Currently only the plotly.expres can use the dataframes from data_manager directly. If we want to create a custom plot using plotly.graph_objects it's not possible due data_manager not have a public method to acces the added dataframes.

Describe the solution you'd like

Add a wrapper for plotly.graph_objects as vizro.plotly.express has

Alternative Solutions

A temporal solution could be add a public method to data_manager that returns a copy of the the dataframe to be used en go.

Additional context

Code of Conduct

Apply minor edits across core docs for enhanced readability

This is a good issue for anyone interested in docs to the point of applying a style guide to some markdown. There's no rewriting required (just small tweaks) and no knowledge of Vizro is expected.

I think the core docs (and probably vizro-ai docs too) could benefit from a minor edit to improve their readability. This would involve the following steps:

  • Creating an informal "lexicon" or style guide (which could be added to the contribution guide)
  • Applying this across the docs
  • Creating a set of tickets if the readability review throws up a need to make further changes beyond minor word choices

How do I get Vizro to run in a Google Colab Notebook?

Question

Im using a Google Colab Notebook due to my need to access a BigQuery instance in which I dont have access to other than via login with a google account.

Im not so sure how to make it work. Using the following snippet doesnt work as expected

Vizro().build(dashboard=dashboard).run()

Code/Examples

No response

Other information

No response

vizro version

No response

Python version

No response

OS

No response

Code of Conduct

ModuleNotFoundError: No module named 'vizro.tables'

Question

my version of Vizro: 0.1.0
Here is my code:
image
I'd like from vizro.tables import dash_data_table
but the terminal will pop up the error: ModuleNotFoundError: No module named 'vizro.tables'

Code/Examples

No response

Other information

No response

vizro version

No response

Python version

No response

OS

No response

Code of Conduct

Consider using dbc components to enable dbc.themes

What's the problem this feature will solve?

Following up on: #205 (comment)

Currently, the dashboard looks off if people try to add their dbc.themes as external stylesheets as our components are not only based on dbc components.

Available vizro stylesheets are currently accessible via dashboard.theme but the process for the user to add their own themes is not as straight-forward as dbc-themes. This issue opens several questions:

  • Shall we apply dbc throughout the entire code basis?
  • When is dbc preferable over dcc?
  • How does it align with using components from other libraries (e.g. dash mantine, dash dcc, dash html etc.)?
  • How do we want to simplify the process for the user to create their own themes?

Describe the solution you'd like

Alternative Solutions

Additional context

Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.