plotting multiple variables with stacked plot

22 views (last 30 days)
Doron Joffe
Doron Joffe on 2 Dec 2021
I have a table in Matlab which summarises the number of votes a fruit got on a particular day.
I want to create a plot in Matlab with the day on the x-axis, the number of votes on the y axis and a line plot for each fruit. I have included an image of the required graph that was done on Excel. Is this possible on Matlab? I have converted the fruit name and days of the week to categorical arrays. Is there a way to create two separate plots for the apple and banana and then combine into one?
  1 Comment
Yes, it's absolutely possible. please refer the plot function with additional features.

Sign in to comment.

Answers (1)

Alagu Sankar Esakkiappan
Alagu Sankar Esakkiappan on 6 Dec 2021
I gather that you need to generate two separate plots for Apple and Banana in the same plot. It is possible to create the same using MATLAB. You may make use of plot function to plot Weekdays against Number of Votes. Legends may then be plotted in the corresponding order using legend function
You may refer to the following sample code to achieve the target plot :
% Read Data from Excel Sheet as a Table in Matlab
fruitTable = readtable("fruitVotes.xlsx");
% Conversion of Fruit Names and Week Days in Table to Categorical Arrays
fruitTable.Fruit = categorical(fruitTable.Fruit);
fruitTable.WeekDay = categorical(fruitTable.WeekDay);
% Gather Row Indices for each Fruit Type ( Refer Logical Indexing for Arrays )
appleIdx = ( fruitTable.Fruit == 'Apple' );
bananaIdx = ( fruitTable.Fruit == 'Banana' );
% Plot Days against Votes for each Fruit ( Refer Plot Documentation )
hold on % Command to draw consecutive plots on top of previous plot
% X, Y axes Labels and Legend Entries
Please refer to the following for further information:
  1. To Separate Rows based on Fruit, Refer Logical Indexing in Matrix Indexing
  2. If rows in Excel Sheet are not already sorted based on Weekdays, Use Ordinal Arrays with Weekdays and Perform Sort Operation on Table before proceeding to data plots.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by