Gnuplot:如何从展平的表格中绘制条形图

问题描述 投票:0回答:2

在 gnuplot 中,如何绘制适合聚合键值对形式的扁平表格?例如,给定这个制表符分隔的文件,我如何为

type=foo
绘制条形图,每个
version
一个条形图?

type    version count
foo a   1
foo b   2
foo c   3
bar a   3
bar b   2
bar c   1
baz a   0
baz b   2
baz c   2

额外学分:我如何绘制 k 个子图,每种类型一个(例如

foo
bar
baz

gnuplot
2个回答
1
投票

到目前为止,我还没有找到(或忽略)综合示例来从具有多个(分层)列和无序条目的扁平列表中绘制条形图。因此,这可能是进一步适应和优化的起点。

当然,也可以使用任何外部工具(或 gnuplot 本身)修改数据,以匹配 gnuplot 直方图绘制样式所需的输入格式。检查

help histograms

关于剧本的一些评论:

  • 输入数据中的关键字不必排序。
  • 为第 1 列和第 2 列创建唯一关键字列表。 唯一列表中的顺序(以及图表中的顺序)将按照第一次出现的顺序。
  • 将关键字转换为数字,即相应关键字列表中的索引
  • 输入数据可能包含相同密钥和子密钥的多个条目,例如
    foo a 2
    foo a 4
    foo a 1
    。由于使用了选项
    smooth freq
    ,它们将被总结为
    foo a 7

脚本:

需要 gnuplot>=5.2.0,因为使用了

keyentry
。该脚本可以适应旧版本。

### different ordered bar charts
reset session

$Data <<EOD
# type    version count
bar a   3
baz b   2
bar c   1
baz a   0
foo a   1
foo b   2
foo c   3
bar b   2
baz c   2
EOD

# create a unique list of strings from a column
addToList(list,col) = list.( strstrt(list,'"'.strcol(col).'"') > 0 ? '' : ' "'.strcol(col).'"')
set table $Dummy
    keysA = keysB = ''
    plot  $Data u (keysA=addToList(keysA,1), keysB=addToList(keysB,2), '') w table
unset table

getIndex(keys,key)                      = (_idx=NaN, sum [_i=1:words(keys)] (word(keys,_i) eq key ? _idx=_i : 0), _idx )
myFilter(colD,colF,valF)                = strcol(colF) eq valF ? column(colD) : NaN 
myFilter2(colD,colF1,valF1,colF2,valF2) = strcol(colF1) eq valF1 && strcol(colF2) eq valF2 ? column(colD) : NaN

set style fill solid 0.3
set boxwidth 0.8 
set offsets 1,1,1,0
set datafile missing NaN
set key top center noautotitle
set grid x,y
gap = 1

set multiplot layout 2,2

    plot for [key in keysA] i=getIndex(keysA,key) $Data u (i):(myFilter(3,1,key)):xtic(key) \
         smooth freq w boxes lc i

    plot for [key in keysB] i=getIndex(keysB,key) $Data u (i):(myFilter(3,2,key)):xtic(key) \
         smooth freq w boxes lc i

    plot for [keyA in keysA] for [keyB in keysB] tmp=(i=getIndex(keysA,keyA), j=getIndex(keysB,keyB)) \
        $Data u ((i-1)*(words(keysB)+gap) + j):(myFilter2(3,1,keyA,2,keyB)): \
        xtic(keyB) smooth freq w boxes lc i, \
        for [keyA in keysA] keyentry w boxes lc getIndex(keysA,keyA) ti keyA

    plot for [keyB in keysB] for [keyA in keysA] tmp=(i=getIndex(keysB,keyB), j=getIndex(keysA,keyA)) \
        $Data u ((i-1)*(words(keysA)+gap)+ j):(myFilter2(3,1,keyA,2,keyB)): \
        xtic(keyA) smooth freq w boxes lc i, \
        for [keyB in keysB] keyentry w boxes lc getIndex(keysB,keyB) ti keyB

unset multiplot
### end of script

结果:

enter image description here


0
投票

在 gnuplot 中使用 awk。首先,过滤表中仅包含“foo”行,然后使用 $NF var 生成 x 坐标。使用

plot
选项将此编辑后的文件传递给
with boxes
(请注意 awk 命令周围的引号):

 plot "< gawk '$1 ~ /foo/ {print $NF, $2, $3 }' table.dat " using 1:3:xtic(2) with boxes

您可以在 gnuplot 中将多个绘图添加到单个图表中,因此您可以运行上面的命令来更改过滤器以添加“bar”和“baz”曲线。

© www.soinside.com 2019 - 2024. All rights reserved.