Skip to content

MATLAB - Bar Graph

Bar charts are essential for visualizing and comparing categorical data. MATLAB’s bar function is a versatile tool for creating a wide variety of bar charts, from simple to complex grouped and stacked plots. Modern best practices involve using categorical data types and manipulating graphic objects for fine-grained control.

bar(y)
bar(x, y)
bar(___, style)
bar(___, 'FaceColor', 'flat')
b = bar(___)
  • bar(y): Creates a bar chart of the elements in vector y.
  • bar(x, y): Creates a bar chart of y at the locations specified by x. Modern MATLAB encourages x to be a categorical array for better labeling.
  • bar(___, style): Specifies the style, such as 'grouped' (default) or 'stacked'.
  • bar(___, 'FaceColor', 'flat'): Allows each bar to have a different color, controlled by the CData property.
  • b = bar(___): Returns one or more Bar objects. This is the key to advanced customization.

Example 1: Simple Bar Chart with Categorical Data

Section titled “Example 1: Simple Bar Chart with Categorical Data”

Let’s visualize quarterly sales data. Using a categorical array for the quarters makes the code more readable and the plot labels automatic.

% Sales data
sales = [120, 185, 160, 210];
% Define the categories for the x-axis
quarters = categorical({'Q1', 'Q2', 'Q3', 'Q4'});
% Enforce the specific order of quarters
quarters = reordercats(quarters, {'Q1', 'Q2', 'Q3', 'Q4'});
figure;
bar(quarters, sales);
title('Quarterly Sales Performance');
xlabel('Quarter');
ylabel('Sales (in thousands USD)');
grid on;

Expected Output Description: A bar chart with four bars. The x-axis is labeled ‘Q1’, ‘Q2’, ‘Q3’, ‘Q4’. The y-axis represents the sales values. The plot has a title, axis labels, and a horizontal grid.

Grouped and stacked charts are used to compare multiple data series. Let’s compare the sales of two different products across the quarters.

% Sales data for two products [ProductA, ProductB]
salesData = [120 90; 185 110; 160 140; 210 190];
quarters = categorical({'Q1', 'Q2', 'Q3', 'Q4'});
quarters = reordercats(quarters, {'Q1', 'Q2', 'Q3', 'Q4'});
figure;
% --- Subplot 1: Grouped Bar Chart ---
subplot(1, 2, 1); % Create a 1x2 grid of plots, access the first
bar(quarters, salesData, 'grouped');
title('Grouped Sales Comparison');
ylabel('Sales (in thousands USD)');
legend('Product A', 'Product B');
grid on;
% --- Subplot 2: Stacked Bar Chart ---
subplot(1, 2, 2); % Access the second plot
bar(quarters, salesData, 'stacked');
title('Stacked (Total) Sales');
ylabel('Sales (in thousands USD)');
legend('Product A', 'Product B');
grid on;

Expected Output Description: A figure window containing two plots side-by-side. The left plot is a grouped bar chart, showing two bars (one for each product) at each quarter. The right plot is a stacked bar chart, showing a single bar for each quarter composed of two colored segments representing the sales of each product.

By capturing the Bar object, you gain full control over the plot’s appearance, such as adding value labels or changing individual bar colors.

Example 3: Adding Value Labels and Highlighting the Max Bar

Section titled “Example 3: Adding Value Labels and Highlighting the Max Bar”
% Sales data and categories from Example 1
sales = [120, 185, 160, 210];
quarters = categorical({'Q1', 'Q2', 'Q3', 'Q4'});
quarters = reordercats(quarters, {'Q1', 'Q2', 'Q3', 'Q4'});
figure;
% Get the handle to the bar series object
b = bar(quarters, sales, 'FaceColor', 'flat');
% --- Add text labels on top of each bar ---
% b.YEndPoints provides the y-coordinates for the top of each bar
text(1:length(sales), b.YEndPoints, num2str(sales'), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
% --- Highlight the bar with the maximum value ---
[maxValue, maxIndex] = max(sales);
% CData controls the color of each bar. It's an Nx3 matrix of RGB triplets.
% Initialize all bars to a default blue color
b.CData = repmat([0 0.4470 0.7410], length(sales), 1);
% Change the color of the max bar to green
b.CData(maxIndex, :) = [0.4660 0.6740 0.1880];
title('Quarterly Sales with Max Value Highlighted');
ylabel('Sales (in thousands USD)');
grid on;
ylim([0, max(sales) * 1.2]); % Adjust y-axis limit for better spacing

Expected Output Description: A bar chart of the four quarters. Each bar has its numerical value printed just above it. Three of the bars are blue, while the fourth bar (Q4, the maximum value) is colored green to highlight it.

  • Start at Zero: Bar chart y-axes should always start at zero to avoid exaggerating differences and misleading the viewer.
  • Use barh for Long Labels: If your category labels are long, use barh to create a horizontal bar chart, which provides more space for text.
  • Clarity over Complexity: Choose the simplest chart type that clearly conveys your message. A simple bar chart is often more effective than a complex stacked chart.
  • Color with Purpose: Use color to highlight key findings or to group related data, not just for decoration. Ensure your color choices are accessible to people with color vision deficiencies.