Forum Discussion

Rockz's avatar
Rockz
Icon for Helper I rankHelper I
2 years ago
Solved

How to maintain pie chart legend colors consistent.

Dear Champions,

 

I'm using a Pie chart visual in power Bi and under legends Am using category calculated column to display the sales closed or open in X days and this X will be dynamic as the value changes at back end this X will also change in category. so while changing the color of these categories is also changing. how to keep these categories colors static. this is the category calculated columnCategory=
VAR X = MAX('Table'[Value])
VAR Achieve mins = X * 3 * 60
RETURN
IF(
[Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] <= Achieve mins,
"Closed within " & X & " days",
IF(
[Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] > Achieve mins,
"Closed more than " & X & " days",
IF(
[Status] IN {"Started", "New"} && [ProcessingTime_Mins] <= Achieve mins,
"Open within " & X & " days",
IF(
[Status] IN {"Started", "New"} && [ProcessingTime_Mins] >Achieve mins,
"Open more than " & X & " days",
"Unknown"
)
)
)
)

 

 

Thanks in advance.

  • Anonymous's avatar
    Anonymous
    1 year ago

    Hi  Rockz , 

    I'm afraid the pie chart visual cannot set fixed colors for a dynamic category, but you might consider using a Python visual to achieve this. I've made a test for your reference:

    1\My data source(Table):

    Category Column

     

     

    Category = 
    VAR X = MAX('Table'[Value])
    VAR Achieve_mins = X * 3 * 60
    RETURN
    IF(
    [Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] <= Achieve_mins,
    "Closed within " & X & " days",
    IF(
    [Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] > Achieve_mins,
    "Closed more than " & X & " days",
    IF(
    [Status] IN {"Started", "New"} && [ProcessingTime_Mins] <= Achieve_mins,
    "Open within " & X & " days",
    IF(
    [Status] IN {"Started", "New"} && [ProcessingTime_Mins] >Achieve_mins,
    "Open more than " & X & " days",
    "Unknown"
    )
    )
    )
    )

     

     

     2\Add a python visual

     

     

     

    # The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: 
    
    # dataset = pandas.DataFrame(Category, ID, ProcessingTime_Mins, Status, Value)
    # dataset = dataset.drop_duplicates()
    
    # Paste or type your script code here:
    
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Assign colors based on the starting characters of the Category string
    def get_color(row):
        category = row['Category']
    
        # Use str.startswith() to check the starting characters
        if category.startswith(('Open within')):
            return "red"
        elif category.startswith(('Open more')):
            return "green"
        elif category.startswith(('Closed within')):
            return "yellow"
        elif category.startswith(('Closed more')):
            return "blue"
        else:
            return "black"  # Default color
    
    # Apply color rules
    dataset['Color'] = dataset.apply(get_color, axis=1)
    
    # Count the number of records for each Category
    category_counts = dataset['Category'].value_counts()
    
    # Ensure the color order matches the categories
    colors = [dataset[dataset['Category'] == category]['Color'].iloc[0] for category in category_counts.index]
    
    # Generate pie chart
    fig, ax = plt.subplots()
    ax.pie(category_counts, labels=category_counts.index, colors=colors, autopct='%1.1f%%')
    
    # Display the pie chart
    plt.show()
    
    
    

     

     

    Note: Before using Python visuals, you need to first install R and Python locally, and then install the matplotlib and pandas libraries.

    R: https://cran.r-project.org/bin/windows/base/

    Python: https://www.python.org/downloads/

    How to set Windows environment variables for Python: https://www.youtube.com/watch?v=Y2q_b4ugPWk

    How to Install numpy, pandas and matplotlib Python libraries on Windows:

    Enter the following command in the command line

    pip install matplotlib pandas

    https://www.youtube.com/watch?v=2iswYOPEeHk

     

    Best Regards,

    Bof

2 Replies

  • If you want the colors to be consistent you need to bring your own colors. Have a reference table that lists all possible categories and their assigned color.

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi  Rockz , 

    I'm afraid the pie chart visual cannot set fixed colors for a dynamic category, but you might consider using a Python visual to achieve this. I've made a test for your reference:

    1\My data source(Table):

    Category Column

     

     

    Category = 
    VAR X = MAX('Table'[Value])
    VAR Achieve_mins = X * 3 * 60
    RETURN
    IF(
    [Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] <= Achieve_mins,
    "Closed within " & X & " days",
    IF(
    [Status] IN {"Closed", "Completed"} && [ProcessingTime_Mins] > Achieve_mins,
    "Closed more than " & X & " days",
    IF(
    [Status] IN {"Started", "New"} && [ProcessingTime_Mins] <= Achieve_mins,
    "Open within " & X & " days",
    IF(
    [Status] IN {"Started", "New"} && [ProcessingTime_Mins] >Achieve_mins,
    "Open more than " & X & " days",
    "Unknown"
    )
    )
    )
    )

     

     

     2\Add a python visual

     

     

     

    # The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: 
    
    # dataset = pandas.DataFrame(Category, ID, ProcessingTime_Mins, Status, Value)
    # dataset = dataset.drop_duplicates()
    
    # Paste or type your script code here:
    
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Assign colors based on the starting characters of the Category string
    def get_color(row):
        category = row['Category']
    
        # Use str.startswith() to check the starting characters
        if category.startswith(('Open within')):
            return "red"
        elif category.startswith(('Open more')):
            return "green"
        elif category.startswith(('Closed within')):
            return "yellow"
        elif category.startswith(('Closed more')):
            return "blue"
        else:
            return "black"  # Default color
    
    # Apply color rules
    dataset['Color'] = dataset.apply(get_color, axis=1)
    
    # Count the number of records for each Category
    category_counts = dataset['Category'].value_counts()
    
    # Ensure the color order matches the categories
    colors = [dataset[dataset['Category'] == category]['Color'].iloc[0] for category in category_counts.index]
    
    # Generate pie chart
    fig, ax = plt.subplots()
    ax.pie(category_counts, labels=category_counts.index, colors=colors, autopct='%1.1f%%')
    
    # Display the pie chart
    plt.show()
    
    
    

     

     

    Note: Before using Python visuals, you need to first install R and Python locally, and then install the matplotlib and pandas libraries.

    R: https://cran.r-project.org/bin/windows/base/

    Python: https://www.python.org/downloads/

    How to set Windows environment variables for Python: https://www.youtube.com/watch?v=Y2q_b4ugPWk

    How to Install numpy, pandas and matplotlib Python libraries on Windows:

    Enter the following command in the command line

    pip install matplotlib pandas

    https://www.youtube.com/watch?v=2iswYOPEeHk

     

    Best Regards,

    Bof