MATLAB: Custom Colours of a Pie Chart Sections

pie chart

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

Best Answer

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