12

How to plot a graph from text file values? The text file look like below:

location  count1    count2
HZ        100        193
ES        514        289
FP        70         137
BH        31         187

I want to plot these values as a graph in shell script. In x axis values of location column and y axis values of count1 and count2 column.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
manu
  • 121
  • 1
  • 1
  • 3
  • The obvious plot "/tmp/temp.txt" fails with Bad data on line 1 of file /tmp/temp.txt. I think you may just have to create a version of the file with just numbers, no row/column headers. Alternatively, use something like gnumeric. –  Sep 14 '17 at 15:40

2 Answers2

10

Using the same input file (ex.tsv), and creating a gnuplot script to better control the details

set style data histogram 
set style fill solid border -1
plot for [i=2:3] '/dev/stdin' using i:xtic(1) title col 

and gnuploting the data:

gnuplot -p ex.gnu < ex.tsv

we see the correspondent histogram.

To create a png file (to upload and show in SO) add 2 more lines:

set terminal pngcairo enhanced font "arial,10" fontscale 1.0 size 600, 400 
set output 'out.png'
set style data histogram 
set style fill solid border -1
plot for [i=2:3] '/dev/stdin' using i:xtic(1) title col

enter image description here

JJoao
  • 12,170
  • 1
  • 23
  • 45
9

Working solution for gnuplot v5.0:

Input data file loc.dat:

location  count1    count2
HZ        100        193
ES        514        289
FP        70         137
BH        31         187

gnuplot script locations.plt:

#!/usr/bin/gnuplot -persist

set title "Location data"
set xlabel "location"
set ylabel "count"
set grid
plot "loc.dat" u (column(0)):2:xtic(1) w l title "","loc.dat" u (column(0)):3:xtic(1) w l title ""

  • set title "Location data" - main plot title

  • set xlabel "location" - setting label for x axis

  • set ylabel "count" - setting label for y axis

  • set grid - adding grid to the plot

  • (column(0)):2:xtic(1) - column range, (column(0)) - as the 1st column in the input file has non-numeric values we need to imitate the numeric 1st column as gnuplot expects only numeric values in it

  • w l - means with lines, to join all data points with lines


Interactive launch:

$ gnuplot
gnuplot> load "locations.plt"

Rendered result:

enter image description here

  • Just wanted to mention, note the quotes around locations.plt in the command gnuplot> load "locations.plt", gnuplot requires that, load locations.plt will not work and you will get "internal error : STRING operator applied to undefined or non-STRING variable" if you forget it. – jrh May 23 '19 at 13:45