Is it possible to use indices as xtic values in a

2019-08-22 11:54发布

问题:

In a file with the data in the following structure:

# [year]
"Town A" population
"Town B" population
"Town C" population

# [year2]
"Town A" population
"Town B" population
"Town C" population

# [year3]
"Town A" population
"Town B" population
"Town C" population

I have managed to create a histogram using the following:

set style data histogram
set style histogram columnstacked
p 'file.dat' index '[year]' u 2:key(1) ,\
'' index '[year2]' u 2,\
'' index '[year3]' u 2;

The previous settings produce the graph almost the way I need it, however, I would like to be able to use the index names (tags?) as xtic values, as of this moment, the xtic values are 0, 1, and 2 instead of year, year2 and year3. Can gnuplot use index values as xtics in a histogram with such data structure?

回答1:

I cannot see a way to set this up inside the plot command itself. It's a great idea and I'll push it on as a feature request for gnuplot. The best I can suggest is this, which assumes you know the set of index strings in advance. I show it as an iteration over N because I assume you may really have more than 3 and for larger numbers the iteration is far less typing.

N = 3
array INDEX[N] = [ "[year1]", "[year2]", "[year3]" ]
set xtics 1
set for [i=1:N] xtics add (INDEX[i] i-1)

plot 'file.dat' index INDEX[1] u 2:key(1) ,\
     for [i=2:N] '' index INDEX[i] u 2


回答2:

Two blanks lines needed between data blocks in file.dat:

# [year]
"Town A" 123
"Town B" 543
"Town C" 789


# [year2]
"Town A" 234
"Town B" 666
"Town C" 1000


# [year3]
"Town A" 345
"Town B" 600
"Town C" 800

Gnuplot commands (requires version 5.2.5 or newer)

set style data histogram
set style histogram columnstacked
set style fill solid border lc black
plot 'file.dat' index '[year]' u 2:key(1) title strcol(-2),\
     '' index '[year2]' u 2 title strcol(-2),\
     '' index '[year3]' u 2 title strcol(-2)

Note that column -2 refers to the index value. That much is not new, but version 5.2.5 now allows you to use it in the strcol() function (short name for stringcolumn()). The title and column spacing could be improved.