How assing symbols to the data for plotting
2 次查看(过去 30 天)
显示 更早的评论
Dear folks,
I am trying to plot some data with categories. However, I couldn't manage to plot my data according to the categories and show a legend for them. Therefore, I am asking a little bit help to this issue.
Example data;
Name Brand Mt
Enes Renault 2.6
Avni Tofaş 2.38
Asaf Tofaş 3.06
My experience, I have managed to plot these data with two plot command overlaying each other grouping them by Brand. However, this time, one group of data has 2 line (as Tofaş has two data) and the other has only one line data (as in Renault). Thus, x-axis is confusing and not giving a healty graph.
The other issue with this, I can't label the x-axis according to Name when I plot two graph overlaying.
Thank you
Enes
0 个评论
回答(1 个)
Shivam
2023-9-29
编辑:Shivam
2023-9-29
Hi Enes,
As per my understanding, you want to plot the data by grouping it using "Brand" and showing a legend for each brand. Also, you want to label the x-axis with the corresponding names of data points.
You can plot data using scatter, label each point with its value and corresponding color, and create custom legend markers for legends corresponding to brand names.
You can follow the below workaround to plot the data:
% Example data
names = {'Enes', 'Avni', 'Asaf', 'Brad', 'Sam'};
brands = {'Renault', 'Tofas', 'Beach', 'Renault', 'Beach'};
mtValues = [2.6, 2.38, 3.06 3.85 2.9];
% unique brands and their corresponding colors
uniqueBrand = unique(brands);
colorForBrands = lines(numel(uniqueBrand));
figure;
hold on;
% Iterate over each data point
for i = 1:numel(mtValues)
% Find the index of the brand in unique_brands
brandIndex = find(strcmp(uniqueBrand, brands{i}));
% Plot the data point with the corresponding color
scatter(i, mtValues(i), 50, colorForBrands(brandIndex, :), 'filled');
% Label the point with the corresponding value
text(i, mtValues(i)+0.02, sprintf('%.2f', mtValues(i)), 'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'center');
end
hold off;
% Set the x-axis labels as the names
set(gca, 'XTick', 1:numel(mtValues), 'XTickLabel', names);
% Set the axis labels and title
xlabel('Name');
ylabel('Mt');
title('Data Plot with Categories');
% Set the xlim and ylim
xlim([0.5, numel(mtValues)+2]);
ylim([min(mtValues)-0.5, max(mtValues)+2]);
% Create custom legend markers with correct colors
markers = gobjects(numel(uniqueBrand), 1);
for i = 1:numel(uniqueBrand)
markers(i) = line(nan, nan, 'Marker', 'o', 'LineStyle', 'none', 'MarkerSize', 10, 'MarkerFaceColor', colorForBrands(i, :));
end
% Create the legend with custom markers
legend(markers, uniqueBrand, 'Location', 'best');
I hope the code helps you to produce the desired results.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!