Search code examples
matlabplotbar-chartmatlab-figure

How can I draw a grouped bar plot?


I have computed the precision, recall and f measure for the algorithm. I want to draw bar plot for the three values. Precision = 1*256, recall = 1*256, F-measure = 1*256.

I am getting a figure like this:

Image result

But, I want to draw bar plot like this:

Expected image

I am very new to Matlab programming and I have tried this following code

data = [P_1,R_1,f_1
    P_2,R_2,f_2
    P_3,R_3,f_3
    P_4,R_4,f_4];
b=bar(data);
set(b,{'FaceColor'},{'b';'r';'y'});
grid on;
set(gca,'XTickLabel',{'DEMO1','DEMO2','DEMO3','DEMO4'});
legend('Precision','Recall','F_\beta');

please help me to solve this.

I am attaching the text file which consists of P1, R1 and F1.

Thanks in advance.

EDIT1: we have in total 12 vectors of 256 values, but we have to calculate the mean or median or any value. In the end, you have to compute only one value from P1 to P_1.Thank you so much @EBH


Solution

  • You are almost there, but you have 2 mistakes.

    1. You build data from the whole vector of Precision (P1, P2...) and the other measurements, while with bar you only input the value to be plotted. All the values that bar plots are scalars like here, so you have to do all the statistics before using bar for plotting. In your case, I believe you want to take the average of each of your variables, so P_1 = mean(P1) and R_1 = mean(R1) etc. for all of your variables. Eventually, you will get 12 scalars from you 12 vectors.
    2. Then, you need to arrange correctly that values in a matrix. Each row stands for a group and each column stands for a color. Basically, you did something close but messed up the commas and line brakes.

    All you need to do is to build data correctly (when all the variables within it are scalars):

    data = [P_1 R_1 f_1
        P_2 R_2 f_2
        P_3 R_3 f_3
        P_4 R_4 f_4];
    

    Notice that I removed all commas, because in Matlab you either specify with , and ; the shape of the matrix, or you use spaces and line-breaks. If you mix both you get in trouble...

    So data is 4-by-3, each row is a demo and each column is a measure. With some random data it looks like this:

    data = rand(4,3);
    b = bar(data);
    set(b,{'FaceColor'},{'b';'r';'y'});
    grid on;
    set(gca,'XTickLabel',{'DEMO1','DEMO2','DEMO3','DEMO4'});
    legend('Precision','Recall','F_\beta');
    

    enter image description here