Python, NumPy and MatPlotLib Line Plot Properties

In this guide we will look at assigning a line plot to a variable and then looking up the properties of this line plot and altering them once the line has been made using get and set commands.

Perquisites

We will need the numpy and matplotlib.pylot libraries:

Python

Configuring the Layout of Figures

Before creating any figures, you should adjust your preferences for how you wish to display figures. The default option is inline which means all figures will be printed to the Console as shown:

If instead you want the Figures to be shown as a separate Window, you can change the setting to Automatic. To do this go to Tools → Preferences:

To do this go to Tools → Preferences:

Next on the left hand menu select iPython console:

Select Graphics:

Change the setting from Inline to Automatic:

Select Apply:

Now go to Consoles and Restart the Kernal:

When rerunning your code, your figure will be in a separate window opposed to being inline within the Console:

Note Spyder Version 3.3 may give a stream of errors instead of making a plot. If you have this version (installed by default with the Anaconda March 2019 installer) you should close down Spyder and then update both Anaconda and Spyder. To do this open the Anaconda PowerShell Prompt and type in:

Python

Note it is also possible to toggle between the two settings without restarting the Kernal using the following commands:

Python

In these guides, the setting automatic will be applied and the figures will all be shown as separate windows.

To create a new figure we can use the following function. Leaving the input argument empty will create a new figure:

Python

To view the figure we need to show it:

Python

If no figures are open this will be “Figure 1”. We can also specify the figure number using:

Python

Now that we have Figure 1000, if we once again type in:

Python

We will get Figure 1000 +1 i.e. Figure 1001

The figures can be closes using the x on the top right corner or by using the command close with the input argument being the figure number in our case 1, 1000 and 1001:

Python

The command:

Python

Will close all open figures.

Data Points

Supposing we have recorded the speed of a rocket at the following 6 time points:

\displaystyle \begin{array}{*{20}{c}} {\text{t (s)}} & {\text{v (m/s)}} \\ 0 & 0 \\ {10} & {227.04} \\ {15} & {362.78} \\ {20} & {517.35} \\ {22.5} & {602.97} \\ {30} & {901.67} \end{array}

We can create NumPy arrays from the data:

Python

Creating a Line Plot

We will close any existing figures and create a new figure called figure 1 and show it:

Python

To add a basic line plot using the NumPy variables t and v as x and y we use:

Python

Line Properties

We can set the line to plot to a variable in this case we will assign it to myline

Python

We see that it shows in variable explorer as a list:

We can have a look at it in the variable explorer:

If we double click into this, we can look at the contents of index0 (this gets us to myline[0]). It is worth scrolling through these to see the keywords available.

Within this list we should note there are a number of methods beginning with get and set which we can call up to get and set values respectively:

Python
'#1f77b4'

This is in hexadecimal format, it can also be input as a string of rgb values, one letter abbreviations for primary and secondary colours. See:

Python

For some fields there are dictionaries for the discrete values available:

If we look at LineStyles we get the following:

Python
'-'
Python

And for Markers we get the following:

Python
'None'
Python

We can also have a look at the properties of myline by using the function getp:

Python
    agg_filter = None
    alpha = None
    animated = False
    antialiased or aa = True
    children = []
    clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
    clip_on = True
    clip_path = None
    color or c = #1f77b4
    contains = None
    dash_capstyle = butt
    dash_joinstyle = round
    data = (array([ 0. , 10. , 15. , 20. , 22.5, 30. ]), arra...
    drawstyle or ds = default
    figure = Figure(640x478)
    fillstyle = full
    gid = None
    in_layout = True
    label = _line0
    linestyle or ls = -
    linewidth or lw = 1.5
    marker = None
    markeredgecolor or mec = #1f77b4
    markeredgewidth or mew = 1.0
    markerfacecolor or mfc = #1f77b4
    markerfacecoloralt or mfcalt = none
    markersize or ms = 6.0
    markevery = None
    path = Path(array([[  0.  ,   0.  ],        [ 10.  , 227....
    path_effects = []
    picker = None
    pickradius = 5
    rasterized = None
    sketch_params = None
    snap = None
    solid_capstyle = projecting
    solid_joinstyle = round
    transform = CompositeGenericTransform(     TransformWrapper(  ...
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    xdata = [ 0.  10.  15.  20.  22.5 30. ]
    xydata = [[  0.     0.  ]  [ 10.   227.04]  [ 15.   362.78]...
    ydata = [  0.   227.04 362.78 517.35 602.97 901.67]
    zorder = 2

Some common things to look at from this list are:

Python
1.5
Python
Python
'#1f77b4'
Python
Python
'-'
Python
Python
'None'
Python
Python
6.0
Python
Python
1.0
Python
Python
'#ff0000'
Python
Python
'#ff0000'
Python
Python
'full'
Python

Changing the markeredgewidth to a lower value so we can see the marker in more detail:

Python
Python
'none'
Python
Python
    agg_filter = None
    alpha = None
    animated = False
    axes = [<matplotlib.axes._subplots.AxesSubplot object at ...
    children = [<matplotlib.patches.Rectangle object at 0x0000022...
    clip_box = None
    clip_on = True
    clip_path = None
    constrained_layout = False
    constrained_layout_pads = (0.04167, 0.04167, 0.02, 0.02)
    contains = None
    default_bbox_extra_artists = [<matplotlib.axes._subplots.AxesSubplot object at ...
    dpi = 100.0
    edgecolor = (1.0, 1.0, 1.0, 1.0)
    facecolor = (1.0, 1.0, 1.0, 1.0)
    figheight = 4.78
    figure = None
    figwidth = 6.4
    frameon = True
    gid = None
    in_layout = True
    label = 
    path_effects = []
    picker = None
    rasterized = None
    size_inches = [6.4  4.78]
    sketch_params = None
    snap = None
    tight_layout = False
    transform = IdentityTransform()
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    window_extent = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=6.4, ...
    zorder = 0
Python
No handles with labels found to put in legend.
Python
'_line0'
Python

We can add another line, with all the line settings above specified:

Python

Again we can look up the properties of this line using:

Python
    agg_filter = None
    alpha = None
    animated = False
    antialiased or aa = True
    children = []
    clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
    clip_on = True
    clip_path = None
    color or c = [1.0, 0.0, 0.0]
    contains = None
    dash_capstyle = butt
    dash_joinstyle = round
    data = (array([ 0. , 10. , 15. , 20. , 22.5, 30. ]), arra...
    drawstyle or ds = default
    figure = Figure(640x478)
    fillstyle = right
    gid = None
    in_layout = True
    label = Rocket 2
    linestyle or ls = :
    linewidth or lw = 5.0
    marker = o
    markeredgecolor or mec = k
    markeredgewidth or mew = 1
    markerfacecolor or mfc = [0.0, 0.6901960784313725, 0.3137254901960784]
    markerfacecoloralt or mfcalt = [0.0, 0.6901960784313725, 0.9411764705882353]
    markersize or ms = 25.0
    markevery = None
    path = Path(array([[   0.  ,    0.  ],        [  10.  ,  ...
    path_effects = []
    picker = None
    pickradius = 5
    rasterized = None
    sketch_params = None
    snap = None
    solid_capstyle = projecting
    solid_joinstyle = round
    transform = CompositeGenericTransform(     TransformWrapper(  ...
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    xdata = [ 0.  10.  15.  20.  22.5 30. ]
    xydata = [[   0.      0.  ]  [  10.    454.08]  [  15.    7...
    ydata = [   0.    454.08  725.56 1034.7  1205.94 1803.34]
    zorder = 2

Now if we wanted to remove this line we could use:

Python

Axes Properties

We can have a look at the axes properties in the variable explorer by opening up myline and selecting index 0:

Then selecting the axes:

Here we get another huge list:

This huge list has a lot of values corresponding to the different plot types. To access this we type in:

Python

We can get the properties by typing in:

Python
    adjustable = box
    agg_filter = None
    alpha = None
    anchor = C
    animated = False
    aspect = auto
    autoscale_on = True
    autoscalex_on = True
    autoscaley_on = True
    axes_locator = None
    axisbelow = line
    children = [<matplotlib.lines.Line2D object at 0x000002265F84...
    clip_box = None
    clip_on = True
    clip_path = None
    contains = None
    data_ratio = 60.11133333333333
    default_bbox_extra_artists = [<matplotlib.lines.Line2D object at 0x000002265F84...
    facecolor = (1.0, 1.0, 1.0, 1.0)
    fc = (1.0, 1.0, 1.0, 1.0)
    figure = Figure(640x478)
    frame_on = True
    geometry = (1, 1, 1)
    gid = None
    gridspec = GridSpec(1, 1)
    images = <a list of 0 AxesImage objects>
    in_layout = True
    label = 
    legend = Legend
    legend_handles_labels = ([<matplotlib.lines.Line2D object at 0x000002265F8...
    lines = <a list of 1 Line2D objects>
    navigate = True
    navigate_mode = None
    path_effects = []
    picker = None
    position = Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=...
    rasterization_zorder = None
    rasterized = None
    renderer_cache = <matplotlib.backends.backend_agg.RendererAgg objec...
    shared_x_axes = <matplotlib.cbook.Grouper object at 0x000002265ACD...
    shared_y_axes = <matplotlib.cbook.Grouper object at 0x000002265AD2...
    sketch_params = None
    snap = None
    subplotspec = <matplotlib.gridspec.SubplotSpec object at 0x00000...
    title = 
    transform = IdentityTransform()
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    window_extent = TransformedBbox(     Bbox(x0=0.125, y0=0.109999999...
    xaxis = XAxis(80.000000,52.580000)
    xaxis_transform = BlendedGenericTransform(     CompositeGenericTrans...
    xbound = (-1.5, 31.5)
    xgridlines = <a list of 9 Line2D xgridline objects>
    xlabel = time (s)
    xlim = (-1.5, 31.5)
    xmajorticklabels = <a list of 9 Text xticklabel objects>
    xminorticklabels = <a list of 0 Text xticklabel objects>
    xscale = linear
    xticklabels = <a list of 9 Text xticklabel objects>
    xticklines = <a list of 18 Line2D xtickline objects>
    xticks = [-5.  0.  5. 10. 15. 20.]...
    yaxis = YAxis(80.000000,52.580000)
    yaxis_transform = BlendedGenericTransform(     BboxTransformTo(     ...
    ybound = (-90.167, 1893.5069999999998)
    ygridlines = <a list of 10 Line2D ygridline objects>
    ylabel = 
    ylim = (-90.167, 1893.5069999999998)
    ymajorticklabels = <a list of 10 Text yticklabel objects>
    yminorticklabels = <a list of 0 Text yticklabel objects>
    yscale = linear
    yticklabels = <a list of 10 Text yticklabel objects>
    yticklines = <a list of 20 Line2D ytickline objects>
    yticks = [-250.    0.  250.  500.  750. 1000.]...
    zorder = 0

Once again we can use set and get to change the properties. Note this is the properties of the axes. For example the facecolor is the colour of the axes and is set to non-transparent white:

Python
(1.0, 1.0, 1.0, 1.0)

We can change this to a transparent green using:

Python

We can look at the axis labels by using:

Python
''
Python
Text(0.5, 23.302222222222213, 'time (s)')

For the y-axis:

Python
''
Python
Text(29.472222222222214, 0.5, 'velocity (m/s)')

For the title:

Python
''
Python

Now we will have a look at altering some of the properties of the x-axis, similar modifications can be made to the y-axis:

Python
'linear'
Python

For the y axis use yscale.

Python
(0.2, 2000.0)
Python

For the yaxis use ylim

Python

For the yaxis use xticks

Python
array([-10.,   0.,  10.,  20.,  30.,  40.,  50.,  60.])
Python
Python
<a list of 7 Text xticklabel objects>
Python
[Text(-5, 0, 'a'),
 Text(5, 0, 'b'),
 Text(15, 0, 'c'),
 Text(25, 0, 'd'),
 Text(35, 0, 'e'),
 Text(45, 0, 'f'),
 Text(55, 0, 'g')]

For the yaxis use yticklabels

Python

We can also enable minorticks by using:

Python

Now we see the minor tick marks, if we want solid major gridlines and dotted minor gridlines we can use:

Python

We can also set the argument to both and this will add x and y major gridlines

Python

Tick Parameters

Returning to the chart before x-ticks were added:

Instead of changing the xticks on the x-axis and replacing the new values with letters. We will instead look to increase the font size on the axis using Tick Parameters. This is found under Index 0 of myline:

Then under axes:

Unfortunately there is no list of get and set for tick_params and getp comes up empty:

Python
 

However we can open up the doc to get a bit of information:

We can change the font size of the x-axis to 18 for example by setting axis to x and changing the labelsize.

Python

Alternatively we can set the axis to both to alter the text of both x and y ticks.

Python

We can also specify the direction of the tick, the width and the length of a tick and colour using:

Python

Changing direction to in:

Python

It is also possible to change the label colour and label rotation:

Python

It is also possible to move the x-axis to the top or the y-axis to the right using:

Python

yaxis or yaxis

To move the ylabel, we need to access the y-axis or x-axis using:

Then once again we see a list of set and get commands:

We are interested in the label position, we can set it to the right:

Python
'left'
Python

To modify the label itself, we need to go to label:

Once again we get a list of items that we can get or set:

Python
    agg_filter = None
    alpha = None
    animated = False
    bbox_patch = None
    children = []
    clip_box = None
    clip_on = True
    clip_path = None
    color or c = black
    contains = None
    figure = Figure(640x478)
    fontfamily or family = ['sans-serif']
    fontname or name = DejaVu Sans
    fontproperties or font_properties = :family=sans-serif:style=normal:variant=normal:wei...
    fontsize or size = 24.0
    fontstyle or style = normal
    fontvariant or variant = normal
    fontweight or weight = normal
    gid = None
    horizontalalignment or ha = center
    in_layout = True
    label = 
    path_effects = []
    picker = None
    position = (610.4166666666666, 0.5)
    prop_tup = (610.4166666666666, 0.5, 'velocity (m/s)', 'black'...
    rasterized = None
    rotation = 90.0
    rotation_mode = anchor
    sketch_params = None
    snap = None
    stretch = normal
    text = velocity (m/s)
    transform = BlendedAffine2D(     IdentityTransform(),     Bbox...
    transformed_clip_path_and_affine = (None, None)
    unitless_position = (610.4166666666666, 0.5)
    url = None
    usetex = False
    verticalalignment or va = top
    visible = True
    window_extent = Bbox(x0=610.4166666666666, y0=122.60999999999999, ...
    wrap = False
    zorder = 3

In this case we want to look at the label colour:

Python
'black'
Python
Python

For the title it is similar:

Python
Python

To move the xlabel position we can use set label coords. Here we specify x and y c0-ordinates as fractions of the size of the chart window.

Python

Spines

We can modify the properties of the spines by indexing into spines and then selecting the spine key:

Once again there is a list of methods beginning with get and set:

Let’s take the left spine and set the colour, line width and line style:

Python

The same settings can be applied for the other spines:

Python

Figure

In order to change the properties of the figure, we need to select figure:

Once again we get a list of get and set:

Python
    agg_filter = None
    alpha = None
    animated = False
    axes = [<matplotlib.axes._subplots.AxesSubplot object at ...
    children = [<matplotlib.patches.Rectangle object at 0x0000021...
    clip_box = None
    clip_on = True
    clip_path = None
    constrained_layout = False
    constrained_layout_pads = (0.04167, 0.04167, 0.02, 0.02)
    contains = None
    default_bbox_extra_artists = [<matplotlib.axes._subplots.AxesSubplot object at ...
    dpi = 100.0
    edgecolor = (1.0, 1.0, 1.0, 1.0)
    facecolor = (1.0, 1.0, 1.0, 1.0)
    figheight = 4.78
    figure = None
    figwidth = 6.4
    frameon = True
    gid = None
    in_layout = True
    label = 
    path_effects = []
    picker = None
    rasterized = None
    size_inches = [6.4  4.78]
    sketch_params = None
    snap = None
    tight_layout = False
    transform = IdentityTransform()
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    window_extent = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=6.4, ...
    zorder = 0
Python
Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.