0

I have two datasets of data printed on the same graph. What I want is to differentiate the information by putting a legend that indicates the color of each of the two pieces of information in the graph.

I have not been able to put a different color to each information and also a legend that shows what data each color belongs to.

My code:

.
.
.  
%grafica de barras 1
bar(app.CasosUIAxes,data1.dateRep,data1.cases,'r')
        
%grafica de barras 2
bar(app.CasosUIAxes,data2.dateRep,data2.cases)

%personalizacion de la grafica
text = strcat('Casos por día en:',{' '}, pais1,{' '},'vs',{' '},pais2) ;
legend(app.CasosUIAxes,text,'Location',"northwest")
xlabel(app.CasosUIAxes,'Fecha')
ylabel(app.CasosUIAxes,'Cantidad de casos')
axis(app.CasosUIAxes,'tight')
xtickangle(app.CasosUIAxes,90)
grid(app.CasosUIAxes,"on")
.
.
.

image

You can only differentiate the lighter bars from the dark ones. The idea is to change that color to a color, for example a red and black, and at the same time in the legend show the indications of these two colors.

1 Answer 1

2

You can try this:

bar(app.CasosUIAxes, data1.dateRep, data1.cases, 'r') 
bar(app.CasosUIAxes, data2.dateRep, data2.cases, 'b')

For adding legend to bar graphs,

b1 = bar(x, y1);
hold on
b2 = bar(x, y2);
legend([b1 b2],'Bar Chart 1','Bar Chart 2')

Source: MATLAB Documentation Page

2
  • For legend, I would recommend you to read this page! since there're multiple ways to add a legend in matlab.
    – william
    Commented Jan 23, 2021 at 4:23
  • b1=bar(app.CasosUIAxes, data1.dateRep, data1.cases, 'r'); hold on b2=bar(app.CasosUIAxes, data2.dateRep, data2.cases, 'y'); hold on legend(app.CasosUIAxes,pais1, pais2) This is my code but it shows me the last bar graph and it is not combined with the first. the legend shows the name of graph one and not the second Commented Jan 24, 2021 at 13:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.