Fortran and Pyplot

Python’s matplotlib.pyplot is a very nice collection of functions that provide an easy Matlab-like interface for data plotting. It can be used to generate quite professional looking plots. There is a lot of information on the internet about calling Fortran from Python, but what if all you want to do is generate some plots from your (modern) Fortran program? With this in mind, I’ve created a very simple Fortran wrapper for Pyplot, allowing you to make pretty good plots by writing only Fortran code. Consider the following example:

program test

    use,intrinsic :: iso_fortran_env, only: wp => real64
    use pyplot_module

    implicit none

    real(wp),dimension(100) :: x,sx,cx,tx
    type(pyplot) :: plt
    integer :: i

    !generate some data:
    x = [(real(i,wp), i=0,size(x)-1)]/5.0_wp
    sx = sin(x)
    cx = cos(x)
    tx = sx * cx

    !plot it:
    call plt%initialize(grid=.true.,xlabel='angle (rad)',&
                        title='python_plot test',legend=.true.)
    call plt%add_plot(x,sx,label='$\sin (x)$',&
    call plt%add_plot(x,cx,label='$\cos (x)$',&
    call plt%add_plot(x,tx,label='$\sin (x) \cos (x)$',&
    call plt%savefig('test.png')

end program test

The main user interface is the pyplot class, which has methods such as initialize, add_plot, and savefig. This example produces the following plot:


All the module does is generate a Python script, and then runs it and saves the result.  The Python call is completely transparent to the Fortran user.

I posted the project to GitHub (pyplot-fortran). Maybe someone else will find it useful, or help to expand it.

See also

  1. matplotlib
  2. F2PY Users Guide and Reference Manual –Fortran to Python interface generator
Posted in Programming Tagged with: , , , , ,
2 comments on “Fortran and Pyplot
  1. Stefano says:

    Great idea!

    I will test it very soon!

    Jacob rocks!

  2. Michael says:

    Just found this on github and was looking for a way to post a message to you. I haven’t looked through your code yet but over the last week I had made some bindings to Python3.4 for Fortran via the ISO_C_BINDING module.. I was actually hoping to use this as a way for making simple fortran GUIs that retains fortran as the base program, as of right now the build has only been tested on win_x64 using Intel Fortran 15..

    I am hoping to eventually move the python code to bytecode and store it in a DLL.. so that it is a self contained library.. I’d like to do something similar for PyQt4/5 if your interested Feel free to contact me: GondekM(AT)my(DOT)erau(DOT)edu
    ^sorry about the copy email address but I am becoming familiar with Regex and its easy enough to start peeling data of the internet…

Leave a Reply

Your email address will not be published. Required fields are marked *