Python matplotlib example xy-plot#

Software requirements:

  • Python 3

  • Numpy

  • matplotlib

Run the xy-plot example script:

python matplotlib_xy_plot.py

Script matplotlib_xy_plot.py:

"""
 DKRZ matplotlib script: matplotlib_xy_plot.py

     - line attributes
     - legend
     - title
     - x-labels, y-labels

 25.06.15 meier-fleischer(at)dkrz.de
"""
import numpy as np
from matplotlib import pyplot as plt

#-----------------------------------------------------------------------
#-- Function: main
#-----------------------------------------------------------------------
def main():

    #-- compute data array
    data = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
    data = data * 5

    #-- plot first data
    plt.plot(data)

    #-- compute next data arrays
    x       = np.arange(100)
    linear  = np.arange(100)
    square  = [v * v for v in np.arange(0,10,0.1)]

    #-- add next lines to plot
    lines   = plt.plot(x,linear,'g--',x,square,'r--')

    #-- get window ID from the first plot
    my_plot = plt.gca()

    #-- define lines, markers and color
    line0 = my_plot.lines[0]
    line0.set_marker('d')
    line0.set_linestyle('--')
    line0.set_color('b')

    #-- set line width and marker style
    plt.setp(lines,linewidth=2)
    plt.setp(lines,markersize=6)
    plt.setp(lines,dashes=[10,5,100,5])

    #-- add a legend
    plt.legend(('data','linear','square'),loc='upper left')

    #-- add a annotations
    plt.title('Title string')
    plt.xlabel('x-axis label')
    plt.ylabel('y-axis label')

    #-- display plot on screen
    #plt.show()

    #-- save to PNG file
    #plt.savefig('plot_matplotlib_xy.png')

    #-- maximize and save to PNG file
    plt.savefig('plot_matplotlib_xy_bbox.png', bbox_inches='tight')

if __name__ == '__main__':
    main()

Plot result:

Matplotlib xy-plot example