WUR Geoscripting -
-Week 3, Tutorial 8: Python -refresher
-Introduction
+ +Python refresher
+Introduction
Good afternoon! Today we will start working with Python for geoscripting and do a refresher of functions in Python. If you are unfamiliar with Python and/or feel that you need more training, follow one of the Datacamp courses as introduction into Python before today:
-
-
- Introduction
+
- Introduction to Python | recommended to follow if you haven’t any scripting experience so far
- Python for R users | recommended if you have experience already in R
Today’s Learning objectives
+Today’s Learning objectives
-
-
Know how to work with virtual environments: Conda + -Mamba
-Know how to run a Python script from the terminal
-Get introduced to Python editors and IDEs
-Refresh Python programming knowledge
-Know how to work with virtual environments: Conda + -Mamba
-Get introduced to Python editors and IDEs
-Familiarize yourself with python Objects and inheritance
-Be able to visualize data using python and matplotlib
+- Know how to work with virtual environments: Conda + +Mamba +
- Get introduced to Python editors and IDEs +
- Familiarize yourself with Python objects and inheritance +
- Be able to visualize data using Python and matplotlib
Introduction to Python
+Introduction to Python
Python is a jack-of-all-trades programming language that is free, flexible, open-source, cross-platform and has a very large community behind it. If you ask Python programmers what they like most about @@ -1088,49 +1011,57 @@
Introduction to Python
Python package management -with Conda
-A set of tools co-exist for installing and managing Python packages.
-It is possible to install packages on your base Python interpreter, but
-sooner or later you will get conflicting Python packages since packages
-have varying dependencies. It can even break
+ A set of tools exist for installing and managing Python packages.
+Although it is possible to install packages on your base Python
+interpreter, sooner or later you will get conflicts between Python
+packages since packages may have varying dependencies. This can even break
your system Python interpreter. Instead, we recommend to use a Python package manager that can make
use of virtual environments, such as Conda or Mamba.
-That way, you can create a conda environment on your machine for each
-project. In conda environments, basically anything, such as software, C
-libraries or R packages can be installed. Here we use them here for
+That way, you can create a Conda environment on your machine for each
+project. In Conda environments, basically anything, such as software, C
+libraries or R packages can be installed. Here we use them for
installing Python packages. Packages installed in one environment do not
-interfere with your base Python or with other conda environments.
+interfere with your base Python or with other Conda environments.
Additionally, it is possible to export and share the requirements for
-your (open source) project with colaborators or users of your code.
+Question 1: Why do you not need to worry about
+environments for scripting in R? Hint: Look back at R
+& Python Basics.
+ For this course, we will make use of Mamba, a fast drop-in
-reimplementation of the Conda package manager. It has its core
+re-implementation of the Conda package manager. It has its core
parts implemented in C++ for maximum efficiency, makes use of parallel
downloading of repository data and package files using multi-threading,
and uses This will install Mamba into Mamba creates isolated conda environments with sets of
-packages, that do not interfere with your base Python or with other
-conda environments. To create an environment: Mamba creates isolated Conda environments with sets of
+packages, that do not interfere with your base Python or with other
+Conda environments. To create an environment: This would create a new environment called geotest with
Python, NumPy and Spyder installed into the
-conda environment. Another option is to create an environment from a
+Conda environment. Another option is to create an environment from a
Let’s first list the currently available environments: Mamba puts an asterisk (*) in front of the active
environment. Now we activate the environment. While Mamba
replaces Conda for most commands, this is not the case for
(de)activating environments: After this, the current environment is shown in parentheses in front
of your prompt ( After creating a conda environment, (additional) Python packages can
+ After creating a Conda environment, (additional) Python packages can
be installed. There are three possible ways to install packages, which
we list below. The This gives a list of all packages that have “pandas” in the name and
lists all available versions. To install: This installs the latest compatible version of Pandas. Note
that this would install it into your currently activated
environment. Note that you can also install multiple packages at the same
time: As you saw with Spyder (which is an IDE, more on that
later), Mamba is also able to install some non-Python packages
that have Python bindings. This is useful for making sure your Python
@@ -1250,67 +1152,38 @@ Removing packages is just as simple: Now, we deactivate the environment and return to base
environment. When we are finished, and do not need the environment for next time,
we can remove the environment Within a conda environment, Python can be started directly, or can be
+ Within a Conda environment, Python can be started directly, or can be
called to run a script file. To start Python directly: Now, you can type Python expressions that will be executed one by
one: To go back, type: Usually, we do not want to run expressions one by one, but build
scripts instead, to ensure transferability and reproducibilty. Create a
new text file and (re)name it (to) The output is printed to the terminal. Running a script from the
terminal is less error-prone than running it from an IDE (see the next
section), such as Spyder, as IDEs often keep variables in memory after
the script has finished running. Therefore, running a script from the
terminal is a good final test before submitting an exercise or
assignment. There are many Integrated Development Environments [IDE] for Python,
and every programmer has their own preference. An IDE is a software
application that provides facilities for software development. Jupyter Notebooks integrate code and visualization, and are therefore
helpful for demonstration purposes. Install Jupyter should pop up in your browser. You will see a menu with all
files in your working directory. The Jupyter Notebook will only see
files that are accessible from the working directory in which you
@@ -1389,20 +1254,15 @@ Type the following Python code in the code cell: Run the code cell by selecting it and pressing the Run
button, or press CTRL + Enter or Shift + Enter. You’ll
see a map visualized below your code, similar to the one below. Try to
drag the map to play around with it. Your Jupyter Notebook is automatically saved as an
The Spyder IDE can be
started in a terminal when the Spyder package is installed in
-the active conda environment. So, using Mamba, make an
+the active Conda environment. So, using Mamba, make an
environment and install Spyder to that environment. Activate the
environment. Spyder will automatically make use of the Python
-interpreter of the active conda environment. To start Spyder: In Spyder you should see an editor, a file explorer and a console.
Have a look at the toolbar. Some important shortcuts are: Open a new file and save it somewhere as In the second part of this tutorial we will refresh your python
+ In the second part of this tutorial we will refresh your Python
knowledge and build upon it. Again, we advise you to code in Spyder, as
-this IDE is the recommended IDE for the python part of this course. First, make a directory structure for this tutorial: We only make a directory for output, because no input data or
separate scripts are created in this tutorial. Next, we will create a
-conda environment from a file. First create a text file in your
+Conda environment from a file. First create a text file in your
preferred text editor, e.g. Now, create a new conda environment based on this file: Now, create a new Conda environment based on this file: Once everything is installed, activate the environment and start
Spyder: Create a new Python script and save it. Important to note: for compatibility, it is best to install packages
from the same channel as much as possible. Given that packages in the
file In the tutorial about R and Python we have gone over the differences
-and similarities of python and R. This tutorial also contains some basic
-python syntax, in this tutorial we assume you know this content, but we
+and similarities of Python and R. This tutorial also contains some basic
+Python syntax, in this tutorial we assume you know this content, but we
will go over a few basics here as well. The example below are mostly
meant for reference purposes, we assume you understand most of this
refresher already. In python we assign variable using the equals sign
+ In Python we assign variable using the equals sign
( Printing in python is done using the Printing in Python is done using the We can use string formatting to use flexible strings, for example for
printing. to start a formatted string, we put a Python is used by a very large community, as is said before. One of
the reasons for this is that this entire community builds a lot of (open
-source) packages. It is therefor very useful to be able to build upon
+source) packages. It is therefore very useful to be able to build upon
these packages. In R you have worked a with dataframes and
spatial dataframes. In Python these are not standard datatypes,
but they are implemented in very well known packages called
In python we import a package using the In Python we import a package using the As you can see we can import a package as something. We use
this if we want to point at specific functionality of this package. If
we want to point at for example the We can create a We can access some information from this The spatial counterpart of a We have now gone over most of the more basic basic functionality of
Python, a lot of similar things you have used in R. A concept we have
not used before is the concept of objects. They have shortly been
@@ -1734,8 +1536,8 @@ In Python, objects are created and manipulated using classes. A class
serves as a blueprint that defines the structure and behavior of
objects. It brings together data (properties) and functions (methods)
@@ -1743,18 +1545,13 @@ In the provided code, the To create an instance of the We have created two objects, This example is straightforward, but keep in mind that classes can
become more complex.
-Question 1: Take a look at the creation of a GeoPandas
- You may have noticed that class definitions differ from what we have
learned. In the However, we previously learned to define a class like this: The difference lies in the code within the parentheses, which
represents inheritance. The class will inherit all the
functionality from the classes specified as arguments, in this case,
In the provided code, the As a result, the In this example,
-Question 2: Create a new class called
+Question 3: Create a new class called
Visualization is essential to make concepts understandable and
patterns recognizable. In Python, Matplotlib is a general
plotting package. It is used as a base for many other, more tailored,
@@ -1914,39 +1678,32 @@ Let’s create a simple line figure, based on data in
Note that the behavior of One can also create multiple subplots (axes) and use different
plotting styles, changing e.g. the marker style, line style, marker
size, and colors. Furthermore, for the upper left subplot it is
demonstrated how to add a legend; adding a label to the plotted line is
essential for this.
-Question 3: In the upper right subplot, why is there no
+Question 4: In the upper right subplot, why is there no
point at x=3, y=8?.
When working with spatial data, it is crucial that the spatial scale
(aspect) in the x and y direction is the same. Because Matplotlib can be
used for plotting any kind of data, not necessarily spatial, it does not
-automatically do this. We can use There are several ways to find help with programming in Python.
Searching the internet typically solves your problem the quickest,
because it finds answers on multiple platforms, such as StackOverflow
@@ -2081,26 +1824,21 @@ See how the objects and functions in the
-Question 4: What kind of functionality does the
+Question 5: What kind of functionality does the
Python package management with Conda
+Mamba installation
+your (open source) project with collaborators or users of your code.
+
+
+Mamba installation
libsolv
for (much) faster dependency solving. To
install Mamba in your Linux environment, we have prepared a
short Bash script for you. Just run the following lines of
code, line by line, in a new terminal window.
-git clone https://github.com/GeoScripting-WUR/InstallLinuxScript.git
-cd InstallLinuxScript/user
-chmod u+x ./install.sh
-./install.sh
git clone https://github.com/GeoScripting-WUR/InstallLinuxScript.git
+cd InstallLinuxScript/user
+chmod u+x ./install.sh
+./install.sh
~/mamba
. Finally,
@@ -1138,67 +1069,53 @@ Mamba installation
Conda in the terminal. Next, let’s see how to use
Mamba in case you want make new virtual environments by
yourself, or install packages after creating the environment.
-Mamba usage
-mamba create --name geotest python numpy
Mamba usage
+.yaml
file, in which all required modules are listed. You
will see an example of this later on in this tutorial. To create an
environment from such a file, you can use the argument
--file
(or --f
in short).
-mamba info --envs
-# Cross-platform (but not always working, like in our VM, so we use the next option)
-conda activate geotest
-
-# Linux, macOS
-source activate geotest
-
-# Windows
-activate geotest
# Cross-platform (but not always working, like in our VM, so we use the next option)
+conda activate geotest
+
+# Linux, macOS
+source activate geotest
+
+# Windows
+activate geotest
(geotest)$
). Note that the activated
environment is only valid for the shell in which you activated it. For
instance, if you close the shell window and open a new one you will have
to activate it again.
-
conda
/mamba
to do so (trying that will
break your environment, because pip does not communicate its
@@ -1212,31 +1129,16 @@ Mamba usage
mamba search
command searches a set of channels. By
default, packages are automatically downloaded and updated from the
default channel. To search for a package, type:
-mamba search pandas
-mamba install pandas
-mamba install geopandas matplotlib
Mamba usage
python --version
or gdal-config --version
to check which Python or GDAL version is used in the environment;which spyder
or type spyder
to find out
-which Spyder executable is used either from system or conda
+which Spyder executable is used either from system or Conda
environment.
-mamba remove geopandas pandas folium
-# Cross-platform
-conda deactivate
-
-# Linux, macOS
-source deactivate
-
-# Windows
-deactivate
geotest
.Running a Python script
-in the terminal
-Running a Python script in the terminal
+
-python
-import sys
-print('Good morning, you are running Python:', sys.version)
-exit()
-# or
-quit()
test.py
. Open it, for
@@ -1318,19 +1191,16 @@ Running a Python script
(
import sys
etc.), and save the script. Navigate in the
terminal to the location where this script is stored, using
cd
. Finally, run the script with:
-
-python test.py
Python editors and IDEs
+Python editors and IDEs
Python editors and IDEs
Spark or PySpark.
Python editors and IDEs
of Spyder, but do know that you will not be assisted for solving
IDE-related issues.Jupyter Notebooks
+Jupyter Notebooks
jupyter
and the
module folium
in an existing or new environment that
includes Python and start Jupyter:
-jupyter notebook
Jupyter Notebooks
markdown. Enter some documentation for your code (e.g. your team name,
exercise and date). Leave the other cell on code.
-import folium
-
-m = folium.Map(location=[51.9700000, 5.6666700], zoom_start=13)
-m
.ipynb
file on your computer (the file extension comes from
the historic name “IPython Notebook”). The notebook can be downloaded as
@@ -1412,25 +1272,17 @@ Jupyter Notebooks
Jupyter Notebook server is running, you cancel the running process. The
terminal goes back to command line and you can exit the virtual
environment by typing conda deactivate
.
-
-Spyder
+Spyder
-spyder
@@ -1443,24 +1295,24 @@
Spyder
main.py
(File –
> New File –> Save As). Test writing a few lines of code and
running the script.Python refresher
-Setting up the environment
-Python refresher
+Setting up the environment
+
-cd ~/Documents/
-mkdir PythonRefresher #or give the directory a name to your liking
-cd ./PythonRefresher
-mkdir output
cd ~/Documents/
+mkdir PythonRefresher #or give the directory a name to your liking
+cd ./PythonRefresher
+mkdir output
gedit
. Then, (re)name it (to)
refresher.yaml
, and copy the following content into the
file:Setting up the environment
- matplotlib
- geopandas
- spyder
-
-mamba env create --file refresher.yaml
-source activate refresher
-spyder
refresher.yaml
are installed from the
conda-forge
channel, it is wise to use this same channel
when you want to install additional packages in your environment.Quick refresher
+Quick refresher
Printing and basic data
-types
-Printing and basic data types
+=
):print
function. We
+print
function. We
can print variables directly:
-# Integer
-age = 25
-
-# Float
-height = 1.75
-
-# String
-name = "John Doe"
-
-# Boolean
-is_student = True
-
-# Print a name
-print(name)
# Integer
+age = 25
+
+# Float
+height = 1.75
+
+# String
+name = "John Doe"
+
+# Boolean
+is_student = True
+
+# Print a name
+print(name)
f
before
the string. We can use curly brackets {}
in this formatted
string. The text between these curly brackets is executed as regular
-python code.
+Python code.
+
# String formatting and printing
-print(f'{name} is {age} years old and is {height} meters tall.)
Basic arithmetic operations:
-
+a = 10
-b = 5
-
-addition = a + b
-subtraction = a - b
-multiplication = a * b
-division = a / b
-modulo = a % b
-exponentiation = a ** b
-
-print(addition, subtraction, multiplication, division, modulo, exponentiation)
Basic arithmetic operations:
+
Conditional statements
-
+x = 15
-
-if x > 10:
- print("x is greater than 10")
-elif x == 10:
- print("x is equal to 10")
-else:
- print("x is less than 10")
Conditional statements
+
Loops (for and while)
-
+# For loop
-for i in range(5):
- print(i)
-
-# While loop
-count = 0
-while count < 5:
- print(count)
- count += 1
Loops (for and while)
+
Lists and basic list
-operations
-
+# Creating a list
-fruits = ["apple", "banana", "orange"]
-
-# Accessing elements
-print(fruits[0]) # Output: "apple"
-
-# Adding elements
-fruits.append("grape")
-
-# Removing elements
-fruits.remove("banana")
-
-# Length of the list
-print(len(fruits)) # Output: 3
Lists and basic list operations
+
Functions
-
+# Function to add two numbers and return the result
-def add_numbers(a, b):
- return a + b
-
-result = add_numbers(5, 3)
-print(result) # Output: 8
Functions
+
Dictionaries
-
+# Creating a dictionary
-person = {
- "name": "Alice",
- "age": 30,
- "is_student": False
-}
-
-# Accessing values
-print(person["name"]) # Output: "Alice"
-
-# Adding a new key-value pair
-person["occupation"] = "Engineer"
-
-# Removing a key-value pair
-del person["is_student"]
Dictionaries
+
Importing packages
+Importing packages
Pandas
and its spatial counterpart GeoPandas.
We will go in much more detail during the Python-Vector tutorial but we
will introduce them quickly here.import
statement
+import
statement
(instead of th the library
function in R) . For example
importing the pandas package goes as follows
-import pandas as pd
read_csv
function from
pandas we we call pd.read_csv
. This function is also
implemented in other packages, but now we are sure we use the pandas
version of this function. Importing pandas is a convention, used very
-widely in the python community.dataframe
as follows:
-
-data = {
- 'Name': ['Alice', 'Bob', 'Charlie'],
- 'Age': [25, 30, 22],
- 'City': ['New York', 'San Francisco', 'Chicago']
-}
-
-df = pd.DataFrame(data)
-print(df)
dataframe
as follows:data = {
+ 'Name': ['Alice', 'Bob', 'Charlie'],
+ 'Age': [25, 30, 22],
+ 'City': ['New York', 'San Francisco', 'Chicago']
+}
+
+df = pd.DataFrame(data)
+print(df)
dataframe
as
follows:
+
# Display the first few rows of the DataFrame
-print(df.head())
-
-# Get statistical information about the DataFrame
-print(df.describe())
-
-# Access a specific column
-print(df['Age'])
GeoDataFrame
-The spatial counterpart of a dataframe
is a ‘GeoDataFrame’,
-which we normally import as gpd
:
-
+import geopandas as gpd
-
-# Dummy data for the GeoDataFrame
-data = {
- 'Name': ['Location A', 'Location B', 'Location C'],
- 'Latitude': [40.7128, 34.0522, 41.8781],
- 'Longitude': [-74.0060, -118.2437, -87.6298]
-}
-
-# Create the GeoDataFrame with a single line of code
-gdf = gpd.GeoDataFrame(data, geometry=gpd.points_from_xy(data['Longitude'], data['Latitude']))
-
-# Display the GeoDataFrame
-print(gdf)
GeoDataFrame
+dataframe
is a
+‘GeoDataFrame’, which we normally import as
+gpd
:import geopandas as gpd
+
+# Dummy data for the GeoDataFrame
+data = {
+ 'Name': ['Location A', 'Location B', 'Location C'],
+ 'Latitude': [40.7128, 34.0522, 41.8781],
+ 'Longitude': [-74.0060, -118.2437, -87.6298]
+}
+
+# Create the GeoDataFrame with a single line of code
+gdf = gpd.GeoDataFrame(data, geometry=gpd.points_from_xy(data['Longitude'], data['Latitude']))
+
+# Display the GeoDataFrame
+print(gdf)
Object-Oriented
-Programming in Python
+Object-Oriented Programming in Python
Object-Oriented
organized programming. Especially when working on projects containing
lots of code OOP will make your work a lot easier to understand for you
and others and it is easier to re-use parts of the code.
-
How to work with objects in
-Python
+How to work with objects in Python
How to work with objects in
class
keyword, followed by the name of the class. Let’s
take a look at an example of a simple class called
Person
:
-
-class Person:
- def __init__(self, name, age):
- self.name = name # < this is a property
- self.age = age # < this is also a property
-
- def greet(self): # < This "function" is a method
- print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
__init__
method is a special
method known as a constructor. It is automatically called when
an object is created from the class. The self
parameter
@@ -1769,35 +1566,23 @@ How to work with objects in
Person
class, you simply
call the class as if it were a function and assign the result to a
variable:
-person1 = Person("Alice", 25)
-person2 = Person("Bob", 30)
person1
and
person2
, which are instances of the Person
class. Now we can access the properties and call the methods of these
objects:
-print(person1.name) # Output: Alice
-print(person2.age) # Output: 30
-person1.greet() # Output: Hello, my name is Alice and I'm 25 years old.
-person2.greet() # Output: Hello, my name is Bob and I'm 30 years old.
print(person1.name) # Output: Alice
+print(person2.age) # Output: 30
+person1.greet() # Output: Hello, my name is Alice and I'm 25 years old.
+person2.greet() # Output: Hello, my name is Bob and I'm 30 years old.
GeoSeries
here.
+Question 2: Take a look at the creation of a GeoPandas
+GeoSeries
here.
It may seem complicated and hard to read, but it is well-documented, so
try to understand some of its functionality. The to_json
method, for example, provides straightforward functionality (though it
@@ -1805,29 +1590,17 @@ How to work with objects in
GeoPandas
example, the class is defined as
follows:
-class GeoSeries(GeoPandasBase, Series):
-class GeoSeries:
GeoPandasBase
and Series
. The
-Series
object refers to the Pandas.Series,
+Series
object refers to the Pandas.Series,
which contains thousands of lines of code with various functionality.
Therefore, the GeoPandas GeoSeries
contains all the
functionality implemented in Pandas, as well as those from
@@ -1845,20 +1618,15 @@ How to work with objects in
object called
Student
, which will inherit all the
properties and methods from the Person
class we defined
earlier.
-
-class Student(Person):
- def __init__(self, name, age, student_id):
- super().__init__(name, age)
- self.student_id = student_id
- self.is_studying = False
-
- def study(self):
- self.is_studying = True
- print(f"{self.name} is studying.")
Student
class inherits from
the Person
class, which we will refer to as the superclass.
By doing so, it extends the functionality of the superclass by adding a
@@ -1869,16 +1637,11 @@ How to work with objects in
Student
class contains both the methods
and properties inherited from the Person
class, as well as
the additional ones defined within the Student
class:
-student = Student("Eve", 22, "123456")
-print(student.name) # Output: Eve
-print(student.student_id) # Output: 123456
-student.greet() # Output: Hello, my name is Eve and I'm 22 years old.
-student.study() # Output: Eve is studying.
student = Student("Eve", 22, "123456")
+print(student.name) # Output: Eve
+print(student.student_id) # Output: 123456
+student.greet() # Output: Hello, my name is Eve and I'm 22 years old.
+student.study() # Output: Eve is studying.
student
is an instance of the
Student
class. It can access the inherited properties from
the Person
class, such as name
, as well as the
@@ -1889,11 +1652,10 @@ How to work with objects in
Student
class. The method study
prints a
message and sets the is_studying
property to
True
.
-
Teacher
. This new class also inherits from
Person
. Define a method for the teacher that checks whether
a student is studying. The student should be an input to the method.
@@ -1901,7 +1663,9 @@ How to work with objects in
Visualization
+Visualization
Visualization
and text. This hierarchy is important to understand when you want to
edit a plot:
NumPy.array
s.
-import numpy as np
-from matplotlib import pyplot as plt
-
-# Create some data
-x = np.arange(-np.pi, np.pi, 0.2)
-y = np.sin(x)
-
-# Plot x against y
-plt.plot(x, y)
-
-# Show the plot
-plt.show()
import numpy as np
+from matplotlib import pyplot as plt
+
+# Create some data
+x = np.arange(-np.pi, np.pi, 0.2)
+y = np.sin(x)
+
+# Plot x against y
+plt.plot(x, y)
+
+# Show the plot
+plt.show()
plt.show()
depends on how you
run the script. If you are using Spyder and want plt.show()
to work:Visualization
meaningful in the context of trigonometric functions and customize the
labels with regular text or lateX. Check if you understand what object
in the hierarchy is edited and why.
-
-import numpy as np
-from matplotlib import pyplot as plt
-
-# Create some data
-x1 = np.arange(-np.pi, np.pi, 0.2)
-y1 = np.sin(x1)
-x2 = np.arange(-np.pi, 0, 0.2)
-y2 = np.cos(x2)
-
-# Initiate a figure with two subplots
-f, axarr = plt.subplots(2, sharex=True)
-
-# Subplots are stored in an array
-line = axarr[0].plot(x1, y1)
-axarr[0].set_title('plot 1')
-axarr[1].plot(x2, y2)
-axarr[1].set_title('plot 2')
-f.suptitle('super title', fontsize=16)
-
-# Axis label
-axarr[1].set_xlabel('x')
-axarr[0].set_ylabel('sin(x)')
-axarr[1].set_ylabel('cos(x)')
-
-# Axis ticks and tick labels
-xticks = axarr[1].get_xticks()
-print(xticks)
-new_ticks = np.arange(-np.pi, np.pi + 0.1, 0.25 * np.pi)
-new_labels = [r"$-\pi$", r"$-\frac{3}{4}\pi$",
- r"$-\frac{1}{2}\pi$", r"$-\frac{1}{4}\pi$",
- "$0$", r"$\frac{1}{4}\pi$",
- r"$\frac{1}{2}\pi$", r"$\frac{3}{4}\pi$",
- r"$2\pi$"]
-axarr[1].set_xticks(new_ticks)
-axarr[1].set_xticklabels(new_labels)
-plt.show()
import numpy as np
+from matplotlib import pyplot as plt
+
+# Create some data
+x1 = np.arange(-np.pi, np.pi, 0.2)
+y1 = np.sin(x1)
+x2 = np.arange(-np.pi, 0, 0.2)
+y2 = np.cos(x2)
+
+# Initiate a figure with two subplots
+f, axarr = plt.subplots(2, sharex=True)
+
+# Subplots are stored in an array
+line = axarr[0].plot(x1, y1)
+axarr[0].set_title('plot 1')
+axarr[1].plot(x2, y2)
+axarr[1].set_title('plot 2')
+f.suptitle('super title', fontsize=16)
+
+# Axis label
+axarr[1].set_xlabel('x')
+axarr[0].set_ylabel('sin(x)')
+axarr[1].set_ylabel('cos(x)')
+
+# Axis ticks and tick labels
+xticks = axarr[1].get_xticks()
+print(xticks)
+new_ticks = np.arange(-np.pi, np.pi + 0.1, 0.25 * np.pi)
+new_labels = [r"$-\pi$", r"$-\frac{3}{4}\pi$",
+ r"$-\frac{1}{2}\pi$", r"$-\frac{1}{4}\pi$",
+ "$0$", r"$\frac{1}{4}\pi$",
+ r"$\frac{1}{2}\pi$", r"$\frac{3}{4}\pi$",
+ r"$2\pi$"]
+axarr[1].set_xticks(new_ticks)
+axarr[1].set_xticklabels(new_labels)
+plt.show()
-from matplotlib import pyplot as plt
-
-x = [1, 2, 3, 4, 5]
-y = [6, 7, 8, 9, 10]
-
-# New: define number of rows and columns of subplots and unpack them directly
-# into variables that then each contain one axes object
-f, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2)
-
-# Dashed line, label for legend, and show the legend on the subplot
-ax0.plot(x, y, 'r--', label='red dashed line')
-ax0.legend(loc='lower right')
-
-# Scatter plot, using a colormap based on the y-value, changing the marker size to 35
-ax1.scatter(x, y, c=y, cmap='bwr', s=35)
-
-# Bar chart, changing the bar color to black
-ax2.bar(x, y, color='k')
-
-# Horizontal bar chart, changing the bar color to yellow
-ax3.barh(x, y, color='y')
-plt.show()
from matplotlib import pyplot as plt
+
+x = [1, 2, 3, 4, 5]
+y = [6, 7, 8, 9, 10]
+
+# New: define number of rows and columns of subplots and unpack them directly
+# into variables that then each contain one axes object
+f, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2)
+
+# Dashed line, label for legend, and show the legend on the subplot
+ax0.plot(x, y, 'r--', label='red dashed line')
+ax0.legend(loc='lower right')
+
+# Scatter plot, using a colormap based on the y-value, changing the marker size to 35
+ax1.scatter(x, y, c=y, cmap='bwr', s=35)
+
+# Bar chart, changing the bar color to black
+ax2.bar(x, y, color='k')
+
+# Horizontal bar chart, changing the bar color to yellow
+ax3.barh(x, y, color='y')
+plt.show()
plt.axis('equal')
, or
-ax.set_aspect('equal')
on the axis, to ensure equal scales
+automatically do this. We can use plt.axis('equal')
, or
+ax.set_aspect('equal')
on the axis, to ensure equal scales
in both directions. Let’s test this on the non-spatial data in the plots
above, see what happens (make sure to adjust the code above properly,
and replace plt.show()
with the code below). Adjust the
Spyder working directory by clicking on the directory icon in the top
right pane if necessary.
+
+
ax0.set_aspect('equal')
-ax1.set_aspect('equal')
-ax2.set_aspect('equal')
-ax3.set_aspect('equal')
-plt.savefig('output/equal_scale.png')
Python help
+Python help
Python help
Asking your friends or colleagues in person is also a great way to learn
and fix programming problems. Another good option is get documentation
from the package website or inside Python:
-
-import sys
-help(sys)
sys
package got
listed.
sys
package provide?
What have we learned?
+What have we learned?
-What have we learned?
More info
+More info
More info
guide
+
+