对如何打印直方图感到困惑?

时间:2014-02-26 06:59:31

标签: c

因此在我的代码中能够计算每个单词的长度并根据单词长度递增索引。我希望能够打印垂直直方图。我尝试了几种不同的方法,但似乎无法使其发挥作用。下面显示的代码打印出您看到单词长度为7的次数。我可以复制已经对这个问题有答案的某人的代码,但我真的想知道如何构建初始骨架,最重要的是我的数据被填充以构建直方图。我真的想解释它是如何工作的!该程序来自C Programming Ritchie和Kernighan。第1.6章练习13.提前感谢您的帮助。

#include <stdio.h>

int main()
{
    int c, wc, i;
    int lenword[10];
    wc = 0;

    for(i=0;i<10;i++)
    {
        lenword[i] = 0;
    }

    while((c=getchar()) != EOF && wc < 10) //Thanks to ClapTrap point out adding wc<10
    {
        if (c == ' ' || c == '\t' || c == '\n')
        {
            if (wc > 0)
            {
                lenword[wc - 1]++;
                wc = 0;
            }
        }
        else
        {
            wc++;
        }
    }

    for(i=0; i<10; i++)
    {
        printf("Length of index = %d is %d\n", i + 1, lenword[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

如果可以使用,我建议使用gnuplot(GPL许可,因此可以免费使用)。你可以在Linux系统上使用它,也可以在windows下载它,虽然我只在linux下使用它。

为此你可以打印两列,如

printf("Index\tLength\n");
for(i=0; i<10; i++)
    printf("%d\t%d\n", i + 1, lenword[i]);

然后运行你的编译程序,如

./your-program > word-lengths.data

然后你可以使用嵌入bash脚本的gnuplot脚本,就像这个骨架:

#!/bin/bash

if test $# -lt 1; then
        echo "Usage:"
        echo "  $(basename $0) list_of_gnuplot_data_files"
        echo
        exit
fi

while test "x$1" != "x"; do
        NAME=$(basename ${1%.data})
        gnuplot << EOF
        set title "Diagram title"

        set key left top
        set style data lines
        set grid

        set autoscale x
        set xtics nomirror
        set xlabel "Word lengths"

        set autoscale y
        set ytics nomirror
        set ylabel "Word count"

        set output "${NAME}.png"
        set terminal png nocrop enhanced font verdana 12 size 1900,900
        plot    "${NAME}.data" using 1:2 title columnhead axes x1y1
EOF
        shift
done

所以要使用它你可以写:

./gnuplot-script word-lengths.data

它会创建一个word-lengths.png。你也可以使用纯gnuplot脚本而不用bash部分,但对我来说这是迄今为止最方便的方法。