how do I plot a histogram in c from 2 arrays?
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 |■■■■■■■
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With