MATLAB - Bar Graph
MATLAB - Creating Modern Bar Charts
Section titled “MATLAB - Creating Modern Bar Charts”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.
Syntax
Section titled “Syntax”bar(y)bar(x, y)bar(___, style)bar(___, 'FaceColor', 'flat')b = bar(___)bar(y): Creates a bar chart of the elements in vectory.bar(x, y): Creates a bar chart ofyat the locations specified byx. Modern MATLAB encouragesxto be acategoricalarray 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 theCDataproperty.b = bar(___): Returns one or moreBarobjects. 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 datasales = [120, 185, 160, 210];
% Define the categories for the x-axisquarters = categorical({'Q1', 'Q2', 'Q3', 'Q4'});% Enforce the specific order of quartersquarters = 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.
Example 2: Grouped and Stacked Bar Charts
Section titled “Example 2: Grouped and Stacked Bar Charts”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 firstbar(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 plotbar(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.
Advanced Customization with Bar Objects
Section titled “Advanced Customization with Bar Objects”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 1sales = [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 objectb = bar(quarters, sales, 'FaceColor', 'flat');
% --- Add text labels on top of each bar ---% b.YEndPoints provides the y-coordinates for the top of each bartext(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 colorb.CData = repmat([0 0.4470 0.7410], length(sales), 1);% Change the color of the max bar to greenb.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 spacingExpected 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.
Data Visualization Best Practices
Section titled “Data Visualization Best Practices”- Start at Zero: Bar chart y-axes should always start at zero to avoid exaggerating differences and misleading the viewer.
- Use
barhfor Long Labels: If your category labels are long, usebarhto 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.