Custom Colours of a Pie Chart Sections

12 views (last 30 days)
Hello!
I wonder if it is possible to create a pie chart in such a way so as to have 6 equally sized sections - each of which is coloured in a specific shade of green or red -depending on the percentage input - 100% being the brightest red or green and 10% being very pale green or red. Thanks! Dima

Accepted Answer

Walter Roberson
Walter Roberson on 11 Jan 2012
It was necessary to get rid of the "clc" to get it to work.
Note: the sectors go counter-clockwise in a "pie" chart.
% Program to apply red and green tinted colors to pie segments
% depending on the size of the pie segment.
function test1()
fontSize = 24;
X = [0 0.5 -0.2 0.3 0.8 -0.7];
fig = figure;
ax = axes('Parent', fig);
numberOfSegments = length(X);
rgbmatrix = [1+(X(:) < 0).*X(:), 1-(X(:) > 0).*X(:), 1-abs(X(:))];
hPieComponentHandles = pie(ax, ones(1,numberOfSegments));
title('Pie Chart with Custom Colors', 'Parent', ax, 'fontSize', fontSize);
% Enlarge figure to full screen.
set(fig, 'units', 'normalized', 'outerposition', [0 0 1 1]);
set(fig, 'name', 'Demo by ImageAnalyst & Tanuki', 'numbertitle', 'off')
% Assign custom colors.
for k = 1 : numberOfSegments
% Create a color for this sector of the pie
pieColorMap = rgbmatrix(k,:); % Color for this segment.
% Apply the colors we just generated to the pie chart.
set(hPieComponentHandles(k*2-1), 'FaceColor', pieColorMap);
set(hPieComponentHandles(k*2), 'String', num2str(X(k)), 'FontSize', fontSize );
end
  7 Comments
Dima
Dima on 12 Jan 2012
yes exactly!))) thanks again for clarifying for me to see the logic of this scrip...works superb!))) I also had two questions:
1) you think this pie can be placed over another chart at a specified location based on the axes of the other chart?
2) and one more question - you think the size of this pie can be controlled to place say two different sized pies one over another on the above chart at the exact same location?
thank you very much for your generous assistance!)
Mathieu
Mathieu on 27 Aug 2020
Thank you for this example, very helpfull !

Sign in to comment.

More Answers (6)

Walter Roberson
Walter Roberson on 8 Jan 2012
Not using pie(). You could patch() this together yourself. You might want to start with the circle routines shown in the FAQ
  1 Comment
Dima
Dima on 9 Jan 2012
thanks....do you think you can show me an example of that?
thanks!)

Sign in to comment.


Image Analyst
Image Analyst on 10 Jan 2012
Dima: Try this:
% Create sample data and plot it.
X = [1 1 1 1 1 1 ] ;
numberOfSegments = length(X)
hPieComponentHandles = pie(X);
% Create custom colormap: 0=pure red, 1 = white.
ramp = [0 : 1/(numberOfSegments-1) : 1]'
pieColorMap = [ones(numberOfSegments, 1), ramp, ramp]
% Note: use flipud(pieColorMap) if you want it
% the other way: 0=white, 1 = pure red.
% pieColorMap = flipud(pieColorMap);
% Apply the colors we just generated to the pie chart.
SetPieChartColors(hPieComponentHandles, pieColorMap);
title('Pie Chart with Custom Colors', 'fontSize', fontSize);
  5 Comments
Dima
Dima on 10 Jan 2012
hopefully we are close to it))
Dima
Dima on 10 Jan 2012
you think the code above is able to generate a similarly coloured pie? thanks again!)

Sign in to comment.


Image Analyst
Image Analyst on 8 Jan 2012
Dima:
Try this demo. Save it as test1.m and then run it. I think it will do exactly what you've asked for (and hopefully that's what you want).
% Program to apply red tinted colors to pie segments
% depending on the size of the pie segment.
function test1()
try
clc; % Clear the command window.
workspace; % Make sure the workspace panel is showing.
fontSize = 24;
X = [1 2 3 4 5 6];
hPieComponentHandles = pie(X);
title('Pie Chart with Custom Colors', 'fontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Ask user if they want to apply custom colors.
promptMessage = sprintf('These are the initial colors.\nDo you want to apply custom colors,\nor Cancel to exit the program?');
button = questdlg(promptMessage, 'Continue', 'Continue', 'Cancel', 'Continue');
if strcmp(button, 'Cancel')
return;
end
% Assign custom colors.
numberOfSegments = length(X)
for k = 1 : numberOfSegments
% Create a color for this sector of the pie
fractionOfPie = X(k) / sum(X)
thisColor = [1 1-fractionOfPie 1-fractionOfPie] % Display in command window.
pieColorMap(k,:) = thisColor; % Color for this segment.
% Apply the colors we just generated to the pie chart.
SetPieChartColors(hPieComponentHandles, pieColorMap);
if k < numberOfSegments
promptMessage = sprintf('Applied new color to sector %d,\nContinue or Cancel?', k);
button = questdlg(promptMessage, 'Continue', 'Continue', 'Cancel', 'Continue');
if strcmp(button, 'Cancel')
break;
end
end
end
catch ME
errorMessage = sprintf('Error in function test1.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
return; % from test1
%=====================================================================
% If you apply a colormap, MATLAB has a "feature" where it applies the
% colormap to ALL the axes on the figure, not just the current axes. So if
% you apply a colormap to the current axes (your pie chart) thinking it
% will affect only your pie chart, you will be surprised to find it affects
% all other charts and images on the dialog box. To get around that, use
% this function which the colors of the pie segments and does not affect
% any other objects in the dialog box. You need to pass in
% hPieComponentHandles which you get when you create the pie chart:
% hPieComponentHandles = pie([Value1, Value2, Value3],{'Label 1','Label 2','Label 3'});
% Then make up your color map like this:
% pieColorMap(1,:) = [.22 .71 .29]; % Color for segment 1.
% pieColorMap(2,:) = [.25 .55 .79]; % Color for segment 2.
% pieColorMap(3,:) = [.93 .11 .14]; % Color for segment 3.
% and finally, call this function
% SetPieChartColors(hPieComponentHandles, pieColorMap);
function SetPieChartColors(hPieComponentHandles, PieSegmentColors)
try
numberOfSegments = min([size(PieSegmentColors, 1) length(hPieComponentHandles)])
for s = 1 : numberOfSegments
set(hPieComponentHandles((s-1)*2+1),'FaceColor', PieSegmentColors(s,:));
end
catch ME
errorMessage = sprintf('Error in function SetPieChartColors.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
return; % from SetPieChartColors
  17 Comments
Walter Roberson
Walter Roberson on 9 Jan 2012
No advance computation required:
rgbmatrix = [(X(:) > 0).*X(:), zeros(length(X),1), -(X(:) < 0).*X(:)];
Then slice K is color rgbmatrix(K,:)
Image Analyst
Image Analyst on 9 Jan 2012
If that formula for arriving at colors works for you, then do it before the k loop and then in the loop, you can just do
pieColorMap(k,:) = rgbmatrix(k,:); % Color for this segment.
and get rid of thisColor computation. Heck, you don't even really need the k loop - that was just for tutorial purposes. You could assign the colors all in one call without any loop over k at all:
SetPieChartColors(hPieComponentHandles, rgbmatrix);

Sign in to comment.


Dima
Dima on 10 Jan 2012
Hello Walter and Image Analyst,
I have made the following changes to the code and it now operates without asking for user input. But colours all the segments in one bright red colour. I need each segment to be coloured in its own specific shade of green or red based on this vector
[0 0.5 -0.2 0.3 0.8 -0.7]
where minus values describe the place on the NO COLOUR to bright RED spectrum and positive values describe the place on the NO COLOUR to the bright GREEN colour.....this function -
rgbmatrix = [(X(:) > 0).*X(:), zeros(length(X),1), -(X(:) < 0).*X(:)];
does this?
the updated code:
% Program to apply red tinted colors to pie segments
% depending on the size of the pie segment.
function test1()
clc; % Clear the command window.
workspace; % Make sure the workspace panel is showing.
fontSize = 24;
X = [1 1 1 1 1 1 ] ;
hPieComponentHandles = pie(X);
rgbmatrix = [(X(:) > 0).*X(:), zeros(length(X),1), -(X(:) < 0).*X(:)];
title('Pie Chart with Custom Colors', 'fontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Assign custom colors.
numberOfSegments = length(X)
for k = 1 : numberOfSegments
% Create a color for this sector of the pie
fractionOfPie = sum(X(1:k)) / sum(X)
thisColor = [1 1-fractionOfPie 1-fractionOfPie] % Display in command window.
pieColorMap(k,:) = rgbmatrix(k,:); % Color for this segment.
% Apply the colors we just generated to the pie chart.
SetPieChartColors(hPieComponentHandles, pieColorMap);
end
%=====================================================================
% If you apply a colormap, MATLAB has a "feature" where it applies the
% colormap to ALL the axes on the figure, not just the current axes. So if
% you apply a colormap to the current axes (your pie chart) thinking it
% will affect only your pie chart, you will be surprised to find it affects
% all other charts and images on the dialog box. To get around that, use
% this function which the colors of the pie segments and does not affect
% any other objects in the dialog box. You need to pass in
% hPieComponentHandles which you get when you create the pie chart:
% hPieComponentHandles = pie([Value1, Value2, Value3],{'Label 1','Label 2','Label 3'});
% Then make up your color map like this:
% pieColorMap(1,:) = [.22 .71 .29]; % Color for segment 1.
% pieColorMap(2,:) = [.25 .55 .79]; % Color for segment 2.
% pieColorMap(3,:) = [.93 .11 .14]; % Color for segment 3.
% and finally, call this function
% SetPieChartColors(hPieComponentHandles, pieColorMap);
function SetPieChartColors(hPieComponentHandles, PieSegmentColors)
try
numberOfSegments = min([size(PieSegmentColors, 1) length(hPieComponentHandles)])
for s = 1 : numberOfSegments
set(hPieComponentHandles((s-1)*2+1),'FaceColor', PieSegmentColors(s,:));
end
catch ME
errorMessage = sprintf('Error in function SetPieChartColors.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
return; % from SetPieChartColors
Thank you for your help!)))

Dima
Dima on 10 Jan 2012
I replaced pieColorMap with rgbmatrix and it still colours all in one bright shade of RED:
% Program to apply red tinted colors to pie segments
% depending on the size of the pie segment.
function test1()
clc; % Clear the command window.
workspace; % Make sure the workspace panel is showing.
fontSize = 24;
X = [1 1 1 1 1 1 ] ;
hPieComponentHandles = pie(X);
rgbmatrix = [(X(:) > 0).*X(:), zeros(length(X),1), -(X(:) < 0).*X(:)];
title('Pie Chart with Custom Colors', 'fontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Assign custom colors.
numberOfSegments = length(X)
for k = 1 : numberOfSegments
% Create a color for this sector of the pie
fractionOfPie = sum(X(1:k)) / sum(X)
thisColor = [1 1-fractionOfPie 1-fractionOfPie] % Display in command window.
pieColorMap(k,:) = rgbmatrix(k,:); % Color for this segment.
% Apply the colors we just generated to the pie chart.
SetPieChartColors(hPieComponentHandles, pieColorMap);
end
%=====================================================================
% If you apply a colormap, MATLAB has a "feature" where it applies the
% colormap to ALL the axes on the figure, not just the current axes. So if
% you apply a colormap to the current axes (your pie chart) thinking it
% will affect only your pie chart, you will be surprised to find it affects
% all other charts and images on the dialog box. To get around that, use
% this function which the colors of the pie segments and does not affect
% any other objects in the dialog box. You need to pass in
% hPieComponentHandles which you get when you create the pie chart:
% hPieComponentHandles = pie([Value1, Value2, Value3],{'Label 1','Label 2','Label 3'});
% Then make up your color map like this:
% pieColorMap(1,:) = [.22 .71 .29]; % Color for segment 1.
% pieColorMap(2,:) = [.25 .55 .79]; % Color for segment 2.
% pieColorMap(3,:) = [.93 .11 .14]; % Color for segment 3.
% and finally, call this function
% SetPieChartColors(hPieComponentHandles, pieColorMap);
function SetPieChartColors(hPieComponentHandles, rgbmatrix)
try
numberOfSegments = min([size(rgbmatrix, 1) length(hPieComponentHandles)])
for s = 1 : numberOfSegments
set(hPieComponentHandles((s-1)*2+1),'FaceColor', rgbmatrix(s,:));
end
catch ME
errorMessage = sprintf('Error in function SetPieChartColors.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
return; % from SetPieChartColors

Dima
Dima on 11 Jan 2012
Hello again!)
I was wondering if the following code can be modified in such a way that is colours each of the sections in each specific shade of green or red based on his vector [0 0.5 -0.2 0.3 0.8 -0.7] :
% Create sample data and plot it.
X = [1 1 1 1 1 1 ] ;
numberOfSegments = length(X)
hPieComponentHandles = pie(X);
% Create custom colormap: 0=pure red, 1 = white.
ramp = [0 : 1/(numberOfSegments-1) : 1]'
pieColorMap = [ones(numberOfSegments, 1), ramp, ramp]
% Note: use flipud(pieColorMap) if you want it
% the other way: 0=white, 1 = pure red.
% pieColorMap = flipud(pieColorMap);
% Apply the colors we just generated to the pie chart.
SetPieChartColors(hPieComponentHandles, pieColorMap);
title('Pie Chart with Custom Colors', 'fontSize', fontSize);
Can you please help me finalize this project?
Thanks a lot!)
  1 Comment
Dima
Dima on 11 Jan 2012
and yes, the following picture shows approximate version of the pie to be drawn with this code:
http://imageshack.us/content_round.php?page=done&l=img36/707/pieh.png&via=mupload&newlp=1

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!