python22.sci2u.dk Active sci2u
Loading...
Login
Prefer latest booklet Prefer latest booklet Login
Link to booklet is copied to clipboard!
Saved to booklet!
Removed from booklet!
Started capturing to booklet.
Stopped capturing to booklet.
Preferring latest booklet.
No longer prefers latest booklet.
Entered edit mode.
Exited edit mode.
Edit mode

Click on the booklet title or a chapter title to edit (max. 30 characters)


How To's

How to get python How to plot points and lines
2.1 Introduction
2.2 Empty figure
2.3 Adding a point
2.4 Rescaling the axes
2.5 Drawing lines
2.6 Titles and labels
2.7 Save figure
How to use loops How to draw general shapes How to draw curves How to use functions How to manipulate Polygons How to create animations How to do mathematical analysis How to fit How to go from SymPy to NumPy How to solve a single differential equation How to do coupled and 2nd order ODEs How to combine vectors and ODEs How to do ODE events Add Chapter..

How to plot points and lines

2.1 Introduction

This chapter will demonstrate how to draw a figure in python inside a jupyter Notebook. The presentation assumes that this is more or less your first experience with python and it therefore introduces every new coding aspect rather elaborately. There are many ways of making drawings in python, some of which may appear simpler than the present one. However, the chosen method is believed to be more readily expandable to larger, more complex figures than most other methods.


2.2 Empty figure

To get started making a figure in jupyter Notebook, you need to write the following three statements:
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
The first line, %matplotlib inline is a jupyter Notebook-specific so-called magic statement which instructs the Notebook to visualize the upcoming figure material within the Notebook cells. This first statement is thus not a python statement and should not be included if you run python outside a jupyter Notebook.
The second line, import matplotlib.pyplot as plt is a python statement that acts to import the standard python library, Matplotlib, so that you can use its functionality in the current jupyter Notebook session. Importing python libraries into python code is a standard first action taken in almost any python program. We shall return to that later. For now it suffices to understand that the matplotlib python library has become available to your session under the name plt.
The third line, fig, ax = plt.subplots() now calls a python function subplots from the matplotlib library. The function returns two python objects which are assigned to the variables fig and ax. Wow take a deep breath. You have now been introduced to a great number of programming terms (library, function, objects, assignment, variable). It may seem overwhelming at this point, but soon you will learn the meaning of all this. For now, type the three lines into a Notebook cell and hit SHIFT-ENTER. This causes the Notebook to produce this figure:

Figure 1



2.3 Adding a point

In order to keep working with the figure we need to address the two python objects, fig and ax. Python objects are programming tools that contain data and means to manipulate the data. The object fig contains among other things information on the size of the canvas (i.e. the paper or the background) for the drawing. We did not specify that when creating fig, so it must have some default value. Likewise, ax contains among other things information about a set of -axes and where on the canvas these axes are to be plotted. Those are parts of the data within the objects. The objects also contain methods to manipulate the data. Invoking e.g.:
ax.plot(1, 3, marker='s')
fig
and hitting SHIFT_ENTER in the jupyter Notebook (in the future, this jupyter Notebook command will be assumed issued without explicit mention herein) you obtain:

Figure 2

The ax.plot(1, 3, marker='s') means that a function is called. The function is the plot-method on the ax-object. When given two values, here and , as the first two arguments, it will plot a marker at the position . Owing to the third argument, marker='s', the marker becomes a square. The second line, fig, is a python statement that outputs a reference to the fig object. In other environments for running python, this causes a bit of gibberish to be output, but in our context, the jupyter Notebook picks up this output and makes sure that an updated version of the figure is drawn as illustrated above. If you use a different framework other than the jupyter Notebook, you might have to write fig.show() to have the figure shown.
Adding more points
You may add further points with different symbols and specify their color:
ax.plot(1, 2, marker='>', color='red')
ax.plot(3, 2, marker='o', color='orange')
fig

Figure 3



2.4 Rescaling the axes

The axis-object has other methods than that used for plotting single symbols. You may for instance decide the extent of the - and -axes yourself with these python statements:
ax.set_xlim([-0.5, 3.5])
ax.set_ylim([-0.2, 3.2])
fig
that invoke (= call a function) the set_xlim- and set_ylim-methods on the axis specified by ax. This time, the arguments are so-called lists, specifying the lower and upper limits wanted. You get this output:

Figure 4



2.5 Drawing lines

The plot method is in fact meant for making entire curves, not just for plotting single points. You specify all the - and all the -values of the points on the curve as the two first arguments to plot. A vertical line from to may e.g. be plotted like this:
ax.plot([0, 0], [1, 3], color='black')
fig

Figure 5

Curves with more line segments can be made by providing longer lists:
ax.plot([1, 1, 2], [1, 0, 0], color='blue')
ax.plot([2.5, 3, 2.75, 2.5], [0, 0, 0.35,0], color='red')
fig

Figure 6



2.6 Titles and labels

You add titles, labels to the axes, and pieces of text within the figure in this manner:
ax.set_title('Title')
ax.set_xlabel('horizontal-x')
ax.set_ylabel('vertical-y')
ax.text(2.5,0.8,'triangle')
fig

Figure 7



2.7 Save figure

Finally, to store the entire figure in a file, you call two methods on the figure-object:
fig.tight_layout()
fig.savefig('nice_fig.png')
The tight_layout method makes sure that axes labels are not cropped in the final figure (don't ask why the user must remember this himself/herself?). The savefig does the expected thing and produces a png-file:

Figure 8

If you give a filename-argument ending in '.pdf' you will get a pdf-file.


Sci2u Assignment: 820
Delete "How To's"?
Once deleted this booklet is gone forever!
Block is found in multiple booklets!

Choose which booklet to go to:

© 2019-2022 Uniblender ApS