Baeldung Pro – Linux – NPI EA (cat = Baeldung on Linux)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

Partner – Orkes – NPI EA (tag=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Introduction

Gnuplot is a command-line utility that we can use to generate plots and charts from mathematical functions and structured data. It supports various output formats, including PNG, SVG, PDF, and EPS, making it a flexible choice for both interactive and scripted plotting. Additionally, by writing simple command sequences, we can visualize trends, compare datasets, and display function curves with clarity and precision.

While Gnuplot can be used interactively, scripting becomes essential when we work with repetitive plotting tasks or large datasets. Moreover, shell scripting can streamline the plotting process by automating command execution, file handling, and output generation. As a result, we reduce manual input, save time, and avoid inconsistencies across multiple plots.

In this tutorial, we’ll explain how to execute Gnuplot commands through shell scripts. First, we’ll cover the basic setup, and then we’ll demonstrate practical scripting methods. After that, we’ll show how to automate tasks such as plotting from multiple files or passing variables into Gnuplot.

2. Setting up the Environment

To begin with, we ensure that Gnuplot is installed on the Linux machine, which we can do using the default package manager.

For example, on Debian-based systems, we leverage apt:

$ sudo apt install gnuplot

After installation, we verify it by checking the version:

$ gnuplot --version
gnuplot 5.4 patchlevel 2

Next, we create a dedicated working directory to organize scripts, data files, and output images. This helps keep the project structured and easier to maintain:

$ mkdir gnuplot-project
$ cd gnuplot-project

With the environment set up, we’re ready to write shell scripts that execute Gnuplot commands and generate plots.

3. Methods to Execute Gnuplot Commands

We can run Gnuplot through the shell in several ways, depending on how much control we need and how complex the plotting task is.

3.1. Using Inline Commands

Inline execution sends Gnuplot instructions directly through the shell. This approach works well for quick plots or simple automation:

$ echo "plot sin(x)" | gnuplot

The command opens a plot window if graphical terminal support is available.

However, graphical output may not work in minimal environments like servers. In these cases, Gnuplot might be able to use the basic terminal setup, which displays the plot as ASCII characters, often making the output more difficult to read.

To that end, to ensure consistent results and avoid terminal issues, we can define an output format:

$ echo "set terminal png; set output 'plot.png'; plot sin(x)" | gnuplot

This way, we save the plot as a PNG file named plot.png in the current directory.

Next, we can open it with any image viewer:

$ xdg-open plot.png

This way, we open the saved plot in a new window as a PNG image:

PNG plot of sin(x) generated by Gnuplot

Sometimes, we want to generate different output filenames without editing the Gnuplot script each time. In such cases, we use dynamic variables, where the shell script controls the content passed to Gnuplot.

For dynamic use, we can pass shell variables into Gnuplot:

$ func="cos(x)"
$ file="graph.png"
$ gnuplot -e "set terminal png; set output '$file'; plot $func"

Here, the func and file variables are passed to Gnuplot using the -e option for flexible automation without separate script files.

After running this command, Gnuplot saves the plot as a PNG image named graph.png:

$ xdg-open graph.png

We can use this method for scripting and batch tasks where direct graphical display is not required.

3.2. Using External Gnuplot Scripts

Inline execution works well for short tasks, but as the plotting commands grow, separating them into a dedicated script becomes more practical.

In this method, we create a separate file that contains Gnuplot commands and call that file from a shell script to improve clarity.

The file we use here is plot_script.gp, which we can create in any text editor or even the shell itself. In this case, the .gp extension stands for Gnuplot. While it may not be required, we add it to distinguish script files.

Inside the file, let’s create a Gnuplot script plot_script.gp:

$ cat plot_script.gp
set terminal png
set output 'graph.png'
plot sin(x) title 'Sine Wave' with lines

Once saved, we create the shell script run_plot.sh to run the Gnuplot script:

$ cat run_plot.sh
#!/bin/bash
gnuplot plot_script.gp

Of course, we also need to give executable permission to the run_plot.sh file before running it:

$ chmod +x run_plot.sh
$ ./run_plot.sh

The command generates a PNG image file named graph.png in the same directory. If we need any changes, we only edit the .gp file.

To pass dynamic output filenames, we can update the shell script:

$ cat run_plot.sh
#!/bin/bash
output_file="dynamic_output.png"
gnuplot -e "outfile='${output_file}'" plot_script.gp

Here, the variable output_file holds the output image name.

Next, let’s update the Gnuplot script to use this variable:

$ cat plot_script.gp
set terminal png
set output outfile
plot cos(x) title 'Cosine Wave' with lines

Now, when we run the run_plot.sh shell script, it sets the value of outfile to output_file when calling Gnuplot. The outfile variable receives that value and is used as the name for the output PNG image. The rest of the commands stay the same, but the name of the output file is now controlled by the shell script.

3.3. Using the Heredoc Method

Another effective way to run Gnuplot commands through a shell script is by using the heredoc method, which embeds commands into the script:

$ cat heredoc_plot.sh
#!/bin/bash
gnuplot <<EOF
set terminal png
set output 'heredoc_plot.png'
plot sin(x) title 'Sine Wave' with lines
EOF

Here, we use <<EOF to begin a command block for Gnuplot that ends at EOF.

Moreover, we can also include shell variables within the heredoc block to make the output dynamic:

$ cat heredoc_plot.sh
#!/bin/bash
output="dynamic_heredoc.png"
function="cos(x)"
gnuplot <<EOF
set terminal png
set output '${output}'
plot ${function} title 'Cosine Wave' with lines
EOF

This approach avoids separate .gp files and keeps all logic within a single script.

4. Plotting Data from Files

So far, we’ve focused on plotting mathematical functions. However, in real scenarios, we often deal with raw data stored in files.

Gnuplot supports direct plotting from text-based data files, including .dat or .txt formats. These files usually contain two or more columns representing x and y values.

4.1. Creating Sample Data

Let’s start by generating a sample data file:

$ cat sample_data.dat
1 3
2 4
3 2
4 5
5 3

This file represents five data points where the first column is the x-axis and the second column is the y-axis.

4.2. Creating the Gnuplot Script

Once the data file is ready, we can write a Gnuplot script to plot it:

$ cat plot_data.gp
set terminal png
set output 'data_plot.png'
plot 'sample_data.dat' using 1:2 with linespoints title 'Data Plot'

Here, using 1:2 tells represents the first column as the x-axis and the second column as the y-axis. Meanwhile, the option with linespoints adds both lines and data points to the plot.

4.3. Creating and Running the Shell Script

Next, we also write a shell script to execute this plotting script:

$ cat run_data_plot.sh
#!/bin/bash
gnuplot plot_data.gp

After that, we save all files and run the shell script:

$ ./run_data_plot.sh

As a result, Gnuplot reads the sample_data.dat file and generates an image named data_plot.png in the same directory:

Gnuplot line chart using sample data

 

The output verifies the successful execution of the plotting script.

5. Automating Plotting from Multiple Data Files

Typically, when we deal with large datasets split across several files, plotting them manually one by one becomes inefficient. Therefore, to handle this, we can automate the plotting process using loops in shell scripts.

For example, let’s assume we have multiple data files named data1.dat, data2.dat, and data3.dat, where each file contains two columns, x and y. Instead of plotting them separately, we write a shell script that loops through each file and generates an individual plot.

We start by creating the data files:

$ echo -e "1 2\n2 3\n3 4" > data1.dat
$ echo -e "1 3\n2 2\n3 5" > data2.dat
$ echo -e "1 4\n2 1\n3 2" > data3.dat

Now, we write a shell script that handles each file automatically:

$ cat batch_plot.sh
#!/bin/bash
for file in data*.dat; do
    output_file="${file%.dat}.png"
    gnuplot -e "datafile='${file}'; outputfile='${output_file}'" <<EOF
set terminal png
set output outputfile
plot datafile using 1:2 with linespoints title datafile
EOF
done

In this script, the for loop goes through each file that matches the data*.dat pattern. Consequently, we create a corresponding PNG file by removing the .dat extension and appending .png.

Then, inside the Gnuplot block, we pass the data file and output as variables to plot each dataset automatically.

6. Conclusion

In this article, we explained how to execute Gnuplot commands through shell scripts for efficient and repeatable plotting.

To begin with, we set up an environment and verified the Gnuplot installation. Then, we explored different methods to run Gnuplot commands, including inline commands, external scripts, and heredoc. Afterward, we moved to real data plotting and ended with automation for multiple datasets.

Overall, each method provides a flexible way to integrate Gnuplot into automated workflows.