Custom Colours of a Pie Chart Sections

15 Ansichten (letzte 30 Tage)
Dima
Dima am 8 Jan. 2012
Bearbeitet: Steven Lord am 28 Mai 2025
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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
  12 Kommentare
Dima
Dima am 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 am 27 Aug. 2020
Thank you for this example, very helpfull !

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (4)

Steven Lord
Steven Lord am 9 Mai 2025
Bearbeitet: Steven Lord am 28 Mai 2025
This wasn't an option when the question was originally asked, but if you're using release R2023b or later you could use the piechart function instead of pie in conjunction with the colororder function.
piechart([1 2 3 4])
colororder([1 0 0; 0 1 0; 0 0 1; 0 0 0])
While I created the list of colors manually for the example above, you can construct a color matrix in a more automated fashion either using vector operations or by passing a named color palette to the colororder function.
Here I'm generating a matrix of six RGB values, each of which has the red component set to 1 with increasing values of the green and blue components.
GBcomponents = linspace(0, 0.9, 6).';
Rcomponent = ones(6, 1);
RGB = [Rcomponent, GBcomponents, GBcomponents]
RGB = 6×3
1.0000 0 0 1.0000 0.1800 0.1800 1.0000 0.3600 0.3600 1.0000 0.5400 0.5400 1.0000 0.7200 0.7200 1.0000 0.9000 0.9000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
After creating a piechart with six wedges, I can use that matrix to set the colors.
piechart([1 2 3 4 5 6])
colororder(RGB)
Or if I like the way some of the color palettes defined on the colororder documentation page look, I can call colororder with that palette name.
piechart(1:6)
colororder("meadow")
As a third option, if you've been using the colormap function with a particular colormap that you like from its documentation page, you could use that function (or one of the predefined colormap functions) to generate an RGB matrix for use with colororder. It's a little early for summer here in Massachusetts but I think it's okay to use the summer colormap for this example.
piechart(1:6)
RGBsummer = summer(6);
colororder(RGBsummer)

Walter Roberson
Walter Roberson am 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 Kommentar
Dima
Dima am 9 Jan. 2012
thanks....do you think you can show me an example of that?
thanks!)

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 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 Kommentare
Dima
Dima am 10 Jan. 2012
hopefully we are close to it))
Dima
Dima am 10 Jan. 2012
you think the code above is able to generate a similarly coloured pie? thanks again!)

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 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 Kommentare
Walter Roberson
Walter Roberson am 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 am 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);

Melden Sie sich an, um zu kommentieren.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by