Custom Colours of a Pie Chart Sections
Ältere Kommentare anzeigen
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
Weitere Antworten (4)
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]
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
am 8 Jan. 2012
2 Stimmen
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
am 9 Jan. 2012
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
Walter Roberson
am 10 Jan. 2012
You need X = [0 0.5 -0.2 0.3 0.8 -0.7]; and
hPieComponentHandles = pie(ones(1,numberOfSegments));
Dima
am 10 Jan. 2012
Dima
am 10 Jan. 2012
Dima
am 10 Jan. 2012
Dima
am 10 Jan. 2012
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
am 9 Jan. 2012
Note: For the user's question, instead of pie(X) use pie(ones(size(X)) or else the portions will not come out equal size.
Dima
am 9 Jan. 2012
Image Analyst
am 9 Jan. 2012
Not sure I understand. If all pie sectors are the same value - the same percentage of the pie - then how can you have different values and different colors depending on the values? All the values would be the same - 1/6th of the whole pie - so all colors would also be the same. I guess I'm just not understanding something.
Walter Roberson
am 9 Jan. 2012
The difference in values is to be represented by color instead of by size.
If the pie() line in your code is changed as I indicate, but the fractionofpie is left to use X, then the aim should be achieved.
Dima
am 9 Jan. 2012
Dima
am 9 Jan. 2012
Image Analyst
am 9 Jan. 2012
Did you figure it out? Just make X=[1 1 1 1 1 1] at the beginning of the program, and modify that one line like Walter said:
fractionOfPie = sum(X(1:k)) / sum(X)
and all slices will be the same size and the colors will go from pale red to pure red. You can easily adapt it for any other colors.
Walter Roberson
am 9 Jan. 2012
I don't think one should set X=[1 1 1 1 1 1] -- one needs the X to have the portion data. I also do not see any reason to take a cumulative sum for the fraction. I still think one should just be changing pie(X) to pie(ones(size(X)); that together with the color changes.
However, I am concerned that input values seem to have been switched to being in the range -1 to +1 . What is meant to calculate a percentage of the total when there is a negative in the mix? Or did the problem get changed on us and it is no longer the _percentage_ that should be considered, and instead the color should simply map according the the value of each entry independent of what the other entries are (not a percentage) ?
Image Analyst
am 9 Jan. 2012
OK I'm getting confused. How are the portions going to be equal-sized if all the X values aren't equal-sized? I took the cumulative sum so that the color could change from slice to slice.
Walter Roberson
am 9 Jan. 2012
The OP wants something pie()-like but not necessarily pie() itself. The slices are to be equal sized dependent only on the number of values, but the coloring for each slice is to be dependent on the values. Two entries that have the same value should produce the same output color.
Originally the question had the color chosen according by percentage, but the OP appears to have changed to instead have the color dependent only upon the individual values.
Dima
am 9 Jan. 2012
Dima
am 9 Jan. 2012
Image Analyst
am 9 Jan. 2012
Dima: Not sure why you're getting 7 sections instead of 6. Well, you see how the colors were assigned. You just have to figure out some scheme to set up r, g, and b such that they range from 0-1. You can pick colors in Photoshop if you want and then divide by 255 to get your numbers in the range of 0-1. If you can't figure it out then let us know what are the 6 colors you want in RGB form (0 to 255). Maybe it won't be a formula like I did - maybe you'll just pick the colors from a custom colormap you made up, like
rgbColor = myColorMap(sectionNumber, :)/255;
Dima
am 9 Jan. 2012
Dima
am 9 Jan. 2012
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
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);
Kategorien
Mehr zu Title finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



