Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to plot a histogram in c

Tags:

c

histogram

how do I plot a histogram in c from 2 arrays?

like image 958
small_potato Avatar asked Sep 14 '25 09:09

small_potato


1 Answers

You could you this character(■) to represent the count in the graph. This is a character that can be printed by

printf("%c", (char)254u);

Consider some random float_arr and hist array that hold the count.

Code

// Function generating random data
for (i = 0; i < n; i++){
    float random = ((float)rand() / (float)(RAND_MAX));
    float_arr[i] = random;
    printf("%f  ", random);
}
//Dividing float data into bins
for (i = 0; i < n; i++){
    for (j = 1; j <= bins; j++){

        float bin_max = (float)j / (float)bins;
        if (float_arr[i] <= bin_max){
            hist[j]++;
            break;
        }
    }
}
// Plotting histogram
printf("\n\nHistogram of Float data\n");
for (i = 1; i <= bins; i++)
{
    count = hist[i];
    printf("0.%d |", i - 1);
    for (j = 0; j < count; j++)
    {
        printf("%c", (char)254u);
    }
    printf("\n");
}

Output

Histogram of Float data
0.0 |■■■■■■■■■■■■■■■■■■■■■■
0.1 |■■■■■■■■■■■■■■■■
0.2 |■■■■■
0.3 |■■■■■■■■■■■■■■
0.4 |■■■■■■■■
0.5 |■■■■■■■■■■■■■■■■
0.6 |■■■■■■■■■■
0.7 |■■■■■■■
0.8 |■■■■■■■■■■■■■■■
0.9 |■■■■■■■
like image 105
Hemanth Kollipara Avatar answered Sep 16 '25 22:09

Hemanth Kollipara