Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Don't miss out! 2025 Microsoft Fabric Community Conference, March 31 - April 2, Las Vegas, Nevada. Use code MSCUST for a $150 discount. Prices go up February 11th. Register now.

Reply
Rockz
Helper I
Helper I

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.

1 ACCEPTED SOLUTION
v-bofeng-msft
Community Support
Community Support

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):

vbofengmsft_0-1727166432339.png

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

vbofengmsft_2-1727168326934.png

 

 

 

# 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

View solution in original post

2 REPLIES 2
v-bofeng-msft
Community Support
Community Support

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):

vbofengmsft_0-1727166432339.png

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

vbofengmsft_2-1727168326934.png

 

 

 

# 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

lbendlin
Super User
Super User

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.

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount! Prices go up Feb. 11th.

Feb2025 Sticker Challenge

Join our Community Sticker Challenge 2025

If you love stickers, then you will definitely want to check out our Community Sticker Challenge!

Jan25PBI_Carousel

Power BI Monthly Update - January 2025

Check out the January 2025 Power BI update to learn about new features in Reporting, Modeling, and Data Connectivity.

Jan NL Carousel

Fabric Community Update - January 2025

Find out what's new and trending in the Fabric community.