Search code examples
pythonuser-interfacehistogramtaipy

How to predefine bar labels in a Taipy histogram with dynamically changing data?


I am currently working on a project where I need to create a histogram using Taipy. The data for the histogram consists of a list of strings, and the criteria for data selection can change dynamically. As a result, the set of occurring strings in the data can also vary. My goal is to predefine the bar labels in the histogram to ensure consistent labeling, regardless of the plotted data. Is there a way to achieve this?

from taipy.gui import Gui

data = {"x":['apple', 'banana', 'apple', 'orange', 'banana', 'mango']}


md = """
<|Change data|button|on_action=update_data|>

<|{data}|chart|type=histogram|x=x|>
"""

def update_data(state):
    state.data = {"x":['apple', 'apple', 'apple', 'orange', 'banana', 'banana']}

Gui(md).run()

Solution

  • You can add some parameters in the layout to predefine x labels. See the code below:

    from taipy.gui import Gui
    
    data = {"x":['apple', 'banana', 'apple', 'orange', 'banana', 'mango']}
    
    # Predefine the bar labels
    bar_labels = ['apple', 'mango', 'banana', 'orange']
    
    xaxis = {"categoryorder":"array",
             "categoryarray":bar_labels}
    
    layout = {"xaxis":xaxis}
    
    md = """
    <|Change data|button|on_action=update_data|>
    
    <|{data}|chart|type=histogram|x=x|layout={layout}|>
    """
    
    def update_data(state):
        state.data = {"x":['apple', 'apple', 'apple', 'orange', 'banana', 'banana']}
    
    Gui(md).run()