plotting multiple variables with stacked plot

4 次查看(过去 30 天)
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 个)

Alagu Sankar Esakkiappan
Hi,
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 )
plot(fruitTable.WeekDay(appleIdx),fruitTable.Votes(appleIdx));
hold on % Command to draw consecutive plots on top of previous plot
plot(fruitTable.WeekDay(bananaIdx),fruitTable.Votes(bananaIdx));
% X, Y axes Labels and Legend Entries
xlabel("Days");
ylabel("Votes");
legend("Apple","Banana","Location","best");
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.

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by