Often, when collecting data for my project, I need to produce multiple plots that result from the same Julia script. Sometimes, I need to run the same script on different days but with slight variations and still want to keep previous versions of my plots without needing to rename the file to which the figure saves. If I do not change the name, the new version of the plot figure will overwrite the old as soon as I run the script. I am lazy and do not want to keep renaming files. 🙂
Here is a simple fix for that issue, which is not an issue but rather a solution that fits my needs.
It can be done using library Dates.jl.
import Dates # import Dates library
Load the plotting library of your choice. I’m using Plots.jl here.
using Plots
Now we create a variable holding the current date.
dt = Dates.today()
2022-06-10 # output
If you wish to include a time stamp, use the following:
dtt = Dates.now()
2022-06-10T10:52:24.854 # at the time of writing this
Let’s produce an example plot to save as a figure. Here I create a dummy range of values to plot for demonstration purposes.
x_vals = collect(Float32, 1:1:10)
10-element Vector{Float32}:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
I used a list comprehension constructor to create the y values.
y_vals = [i * sin(rand(Float32)) for i = 1:1:10 ]
10-element Vector{Float32}:
0.21887748
1.3162528
2.4540956
1.0214962
0.26296785
0.73046935
0.8129427
3.1573246
2.3606932
2.0475461
Now we are ready to plot.
P = plot(x_vals, y_vals, title="My Plot", xlabel="x values", ylabel = "y values", dpi=300)
I usually save my figures as a .png
file containing the date. Notice the
to insert a date AND time). It is called string interpolation or inserting some value, earlier defined by some variable, into a string.
savefig(P, "plotName_$dt.png")
Here is our plot.

And this is how the corresponding file name is showing up in the file explorer.

Mission accomplished. If you run the same script tomorrow, you’ll get the same file name but with a different date in the file name. Now you will have two separate files containing different versions of the same plot.