How to choose color in bar graph
4 views (last 30 days)
Show older comments
I am trying to fix specific colors in my bar graph but i dont know how i can choose multiple colors , red, blue, because each time i run output it changes its color.
clear all
data = readmatrix("4guploadtim.csv")
data2 = readmatrix("4guploadvodafone.csv")
x = data(:,1);
y = data(:,2);
hold on ;
x2 = data2(:,1);
y2 =data2(:,2);
h = bar([x,x2],[y,y2]);
hold off ;
set(gca,"XGrid","on","YGrid","off")
legend (h,"Tim","Vodafone")
xlabel('Location');
ylabel('Upload');
title('Upload speed vodafone 4g upload bar plot (Tim&Vodafone)');
i want the colors to be locked and not change for each run.
1 Comment
Rik
on 10 Nov 2023
What do you mean that the colors change? If you have a fresh axes, the colors should be the same.
Ohterwise, a bar chart follows the colororder. Did you check the documentation to see how you can set the colors?
Answers (1)
Voss
on 10 Nov 2023
The colors appear to change on each run because you're plotting into the same axes (with hold on) each time.
It's the same as plotting several lines without specifying their colors (MATLAB picks the colors based on the axes' ColorOrder property):
hold on
plot(1:10)
plot(2:11)
plot(3:12)
Except in your case the data is always the same, so each newly plotted set of bars is in exactly the same place as the old one, so you only see the last one, which has some new colors.
One way to avoid this is to create a new figure in your code before plotting the bars, so that each run plots into a different figure (hold on and hold off are not necessary in this case):
figure();
x = data(:,1);
y = data(:,2);
% hold on ; % hold on and hold off have no effect in this case and can be removed
x2 = data2(:,1);
y2 =data2(:,2);
h = bar([x,x2],[y,y2]);
% hold off ;
set(gca,"XGrid","on","YGrid","off")
legend (h,"Tim","Vodafone")
xlabel('Location');
ylabel('Upload');
title('Upload speed vodafone 4g upload bar plot (Tim&Vodafone)');
If instead of a new figure for each run, you want to always plot into the same figure, then you can put your hold off before you call bar, so that bar replaces whatever was in the axes (hold on is not necessary in this case):
x = data(:,1);
y = data(:,2);
x2 = data2(:,1);
y2 =data2(:,2);
hold off % turn hold off so that the bars replace whatever was in the axes
h = bar([x,x2],[y,y2]); % create the bars
set(gca,"XGrid","on","YGrid","off")
legend (h,"Tim","Vodafone")
xlabel('Location');
ylabel('Upload');
title('Upload speed vodafone 4g upload bar plot (Tim&Vodafone)');
0 Comments
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!