Fig. 1: Gnuplot called from Fortran

Gnuplot is a free plotting tool that can be run from the command-line or invoked by third-party applications. The plotting commands and the input data are read from files. Plots can either be displayed inside a window (fig. 1) or exported in various formats. Gnuplot is under active development since 1986.

The Fortran example below writes the processed data to a text file data.txt and then uses the intrinsic Fortran routine system() to call Gnuplot. Additional Fortran modules are not required.

! gnuplot.f90
program main
    implicit none
    character(len=*), parameter :: F = 'data.txt'   ! File name.
    integer,          parameter :: U = 20           ! Output unit.
    integer,          parameter :: N = 10           ! Number of values.

    real, dimension(N) :: x, y
    integer            :: i

    x(1) = 0.0
    y(1) = 0.0

    do i = 2, N
        x(i) = 0.1 * i
        y(i) = x(i) * x(i)
    end do

    ! Open data file and write values into it.
    open (unit=U, action='write', file=F, status='replace')

    do i = 1, N
        write (U, *) x(i), y(i)
    end do

    close (U)

    call system('gnuplot -p plot.plt')
end program main

The Gnuplot commands to display the plot are stored in file plot.plt:

# plot.plt
set xlabel "x"
set ylabel "y"
set terminal x11 0
set nokey
set grid
set title "Fortran Example"
plot m using 1:2 with linespoints

This file will be read by Gnuplot to do the actual plotting.

Fortran Libraries

Several implementations of Gnuplot libraries are available: