如何从 2 个数组中绘制 c 中的直方图?
问问题
7686 次
4 回答
2
对于在其一侧布置的直方图...
我建议对每个增量使用 printf("*"),并使用 printf("\n") 开始输出新行。(改变方向是读者的练习)。
于 2010-10-01T07:18:03.437 回答
1
您可以为此使用 ascii 艺术
于 2010-10-01T06:41:20.420 回答
1
稍微考虑一下这个问题,我不相信我在评论中确定的“重复”真的是响应式的。所以我会说几句话。
如果您已经确定了一种 ASCII 艺术方法,那么您只需要再做出一个决定:垂直条还是水平条。水平很容易:只需决定缩放比例,然后bin_contents*scale
为每个 bin 打印符号。code-golf 链接作为一个模型非常有用,即使它不是如何编写它的一个很好的例子。
然而,许多领域在直方图的呈现中都期望垂直条。这有点难,但考虑一下伪代码
sacle = find_scale(input_array)
max_height = find_max(input_array) * scale
for (i=max_height; i>=0; i--)
if (some condition)
print_in_N_digits(round(i/scale)) // to label the scale
else
print_in_N_digits() // lines with no labels
print " |" // set up the vertical axis
for (j=first_bin to lat_bin)
if (input[j]*scale >= i)
print("#")
else
print(" ")
print_new_line
print_in_N_digits(0)
print(" +")
for (j=first_bin to last_bin)
print("-")
print_new_line
print_in_N_digits()
print(" 0")
for (j=first_bin to last_bin)
if (some other condition)
print_bin_label
这只是遍历页面,在每个 bin 的列上使用,并且在每个级别打印一个" "
或"#"
每个列。直方图打印部分真的很容易。所有的复杂性都源于管理轴和标签。
于 2010-10-01T15:58:38.973 回答
1
你可以用这个字符(■)来表示图中的计数。这是一个可以打印的字符
printf("%c", (char)254u);
考虑一些保存计数的随机数float_arr
和hist
数组。
代码
// 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");
}
输出
Histogram of Float data
0.0 |■■■■■■■■■■■■■■■■■■■■■■
0.1 |■■■■■■■■■■■■■■■■
0.2 |■■■■■
0.3 |■■■■■■■■■■■■■■
0.4 |■■■■■■■■
0.5 |■■■■■■■■■■■■■■■■
0.6 |■■■■■■■■■■
0.7 |■■■■■■■
0.8 |■■■■■■■■■■■■■■■
0.9 |■■■■■■■
于 2020-09-21T12:30:20.760 回答