Matt Sal
Matt Sal

Reputation: 41

Different colors and data value on bars: Bar Chart Matlab

I want to plot the scalars TEV_Idz and TEV_TF in a bar chart.

Problem 1: I want to see the legend for two scalars in two different colors, but I only end up getting one where both bar charts have the same blue colors.

Problem 2: I am trying to get the value of each scalar on their respective bar, but I cannot produce an output with the below function.

This is my output:

my undesired output

This is my code:

TEV_plot = bar([TEV_Idz;TEV_TF], 0.6);
grid on;
set(gca, 'yTickLabel',num2str(100.*get(gca,'yTick')','%g%%'));

% PROBLEM 1: The code for having a legend
ii = cell(1,2);
ii{1}='L'; ii{2}='B';     %first bar called L and second bar called B
legend(TEV_plot,ii);      %mylegend

%PROBLEM 2: This is my code for plotting the value of each scalar on the top of the every bar graph.
for k = 1:numel(TEV_plot)
    text(k, TEV_plot(k), {num2str(TEV_plot(k)), ''}, ...
        'HorizontalAlignment', 'center', ...
        'verticalalignment', 'bottom')
end

Upvotes: 0

Views: 549

Answers (1)

Wolfie
Wolfie

Reputation: 30046

Bar plots can only take one colour per series, so we just need to put your data into two series not one! Each series is a matrix row, and each column of the matrix is a different colour, so if we add some 0s (so padding doesn't show as actual bars with any height) you can achieve what you want.

This actually solves problem 1, makes the legend work properly, and makes problem 2 easier!

See code comments for details, note the bar must be 'stacked'

TEV_Idz = 0.0018; TEV_TF = 0.012;
% Each row in a bar plot is its own series, so put the data on two rows.
% This can be created using TEV_data = diag([TEV_Idz, TEV_TF]); 
TEV_data = [TEV_Idz, 0; 
            0,       TEV_TF]; 
% Each column will be a different colour, plot them stacked to be central
TEV_plot = bar(TEV_data, 0.6, 'stacked');
grid on; ylim([0, max(TEV_data(:) + 0.002)]);
set(gca, 'yTickLabel',num2str(100.*get(gca,'yTick')','%g%%'));

% Insert legend, one element for each series
legend({'L','B'}, 'location', 'northoutside', 'orientation', 'horizontal')
% A better option might be to just label on the x axes and not have a legend:
% set(gca, 'xticklabels', {'L','B'})

% Plotting the value of each scalar on the top of the every bar graph.
% The diagonal entries of TEV_data is where the actual data is stored. 
% Use num of diagonal entries, and index (k,k) for diagonal.
for k = 1:numel(diag(TEV_data))
    text(k, TEV_data(k,k), num2str(100.*TEV_data(k,k),'%g%%'), ...
        'HorizontalAlignment', 'center', ...
        'verticalalignment', 'bottom')
end

Output:

bar plot with different colour bars

Upvotes: 1

Related Questions