The tutorials are intended to beginners who wants to start in Python 3.X with a little help.
The tutorials are seperated in mapping and seismogram processing.
Visit (https://www.anaconda.com/products/individual) and download anaconda Open a terminal and create a clean Python enviroment typing:
conda create --name myenv
or with a specific Python version
conda create -n myenv python=3.6
if everything is ok, activate the enviroment:
conda activate myenv or source activate myenv
Inside your enviroment you can install Python packages, for example: conda install numpy or pip install scipy

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Thu Apr 15 09:15:51 2021

@author: robertocabieces

import math
import random

# Numbers and Arithmetic Operators
#Addition x+y
#Subtraction x-y
#Multiplication x*y
#Division x/y
#Truncating division x // y
#Exponentiation x ** y


a = 122 + 20


a = 1.5*4

# complex numbers
z = 1+2j

# special functions


pi = math.pi
a = math.sqrt(45)

# generate random data
a = random.random()

# Implicit conversion and first programm
l=input(“Enter length: “)
b=input(“Enter width: “)
print (“Area of rectangle is”,a)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Sun Apr 11 21:20:11 2021

@author: robertocabieces

# Specific methods for strings
# Find and replace characters and substrings

F = “WM.CHAS..BHZ.262”
F.find(‘WM’) # returns the offset or -1 case False

S = F.replace(‘WM’, ‘ES’)

# Split and convert to lists

ELEMENTS = S.split(‘.’)

# upper and lower
S.lower() #bea aware, this method doesn’t change the string by itself
Elements = S.lower()

####### IMPORTANT format always!!!!!!!!!!!!!!!!!!!

print(“Quality Parameters: Number of Phases {:.2f} “
“Azimuthal GAP {:.2f} Minimum Distance {:.2f} “
“Maximum Distance {:.2f}”.format(3.1345,2.6890,1.23123,1.109010))


# Using Pattern Matching

import re

match = re.match(‘Hello*’, ‘Hello World’)

# Check if something is in a string

print(‘rubbery’ in ‘shrubbery’)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Sun Apr 11 20:52:38 2021

@author: robertocabieces

# Strings and Numbers

# Hello world

print(“Hello World”)

# strings and its atributtes

a = “pepe”

# How long is a string?


# Slice a string


# Concatanate a String

b = “y”
c = “juan”

r = a+ ” ” + b+ ” “+c
# tabs \t and enter \n
r = “Hello\tWorld\n”
# Reptition

rr = a*8

# important string is an inmutable object

#a[0] = “k”

# instead, you must do the following,

S = “k” + a[1:]

# after see what is a list
# convert to a list

L =list(a)

# try typing help(”.join) in the console 2/A

# how to know what is ..

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Thu Apr 15 09:22:08 2021

@author: robertocabieces

# Lists

L = [123, ‘spam’, 1.23]

# run on the terminal

# sliding


# concat

L = L + [4, 5, 6]

# repeat
L = L*2

# specific operations

# sort operations

# add an object
# Nesting = Lista de listas

M = [[0,1], [2,0], [“paco”]]
# select items froma nested list

# using special built-in function

number_list = [1, 2, 3]
str_list = [‘one’, ‘two’, ‘three’]
result = zip(number_list, str_list)

# Find index in a list
test = [1, 0, -1, 2, 4]
index = test.index(min(test))

# Check if an item is in a list
print(0 in test)
print(-2 in test)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Fri Apr 16 09:37:56 2021

@author: robertocabieces

# Dictionaries

D = {‘food’: ‘Spam’, ‘quantity’: 4, ‘color’: ‘pink’}

D[‘food’] # Fetch value of key ‘food’
# print keys


# Create dictionaries

D1 = {}
D1[‘name’] = ‘Bob’
D1[‘job’] = ‘dev’
D1[‘age’] = 40

D2 = dict(name=’Bob’, job=’dev’, age=40)
bob2 = dict(zip([‘name’, ‘job’, ‘age’], [‘Bob’, ‘dev’, 40]))
k = zip([‘name’, ‘job’, ‘age’], [‘Bob’, ‘dev’, 40])
D3 = dict(k)

# Nested dictionaries

D4 = {‘name’: {‘first’: ‘Bob’, ‘last’: ‘Smith’}, ‘jobs’: [‘dev’, ‘mgr’],
‘age’: 40.5}

D4.get(‘name’, 0)
# check if a key is insife a dictionary
# type in the terminal ‘f’ in D

Method Description
clear() Removes all the elements from the dictionary

del D3

copy() Returns a copy of the dictionary

DD = D2.copy()

fromkeys() Returns a dictionary with the specified keys and value

x = (‘key1’, ‘key2’, ‘key3’)
y = (0, 1, 2)

thisdict = dict.fromkeys(x, y)

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary’s keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964

x = car.setdefault(“model”, “Bronco”)

# Very important
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Tue Apr 20 12:42:57 2021

@author: robertocabieces
# Tuples

T1 = ()
T1 = (0,)
T1 = (0, ‘Ni’, 1.2, 3)
T1 = 0, ‘Ni’, 1.2, 3
T1 = (‘Bob’, (‘dev’, ‘mgr’))
T1 = tuple(‘spam’)

# concatanate
T2 = (“Juan”, “Pedro”)
T3 = T1 + T2
T1* 3

# conversion

tmp = list(T1)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Tue Apr 20 12:49:57 2021

@author: robertocabieces

# Conditions

# Theory
if test1: statements1
elif test2: statements2

if test
Associated block # Optional elifs


< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal t
== Equal to
!= Not equal to

Logical Operators


The logical expression connected with the AND logical operator returns trueif all the logical expressions evaluate to true.
The logical expression connected with the orlogical operator returns trueif any of the logical expressions evaluates to true.
The logical expression preceded by the notlogical operator is negated.
That is, the logical expression that evaluates to truebecomes falsewhen preceded by the logical notoperator and vice versa.

# Examples

print(“Please enter a number”)

number = input()
number = int(number)

if number >-1:

print(number, “is bigger than”, “-1”)

print(number, “in lower or equal to”, “-1”)


print(“Please enter a number”)

number = input()
number = int(number)

if (number >= 1 or number <= -1):

print(number, “is outside”, “-1 1”)

elif number == 0:

print(number, “is equal to”, “0”)


print(number, “is inside”, “-1 1”)


# Blocks structure
x = 1
if x:

y= 2

if y:




#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Tue Apr 20 13:21:29 2021

@author: robertocabieces

while expression :

while test: statements
if test: break
if test: continue / pass else:

# Example 1

while k <=10:
print (k)

# breaking the loops

while 1:
print (k)


while k <=10:
if k==7:


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Tue Apr 20 13:21:29 2021

@author: robertocabieces

for target in object:

for target in object: statements
if test: break
if test: continue

for i in range(11):
print (i)

for i in range(1,11):
print (i)

for i in range(1,11,2):
print (i)

# nested for loop
# prime numbers between 1 and 100

for i in range(2,101):
for j in range(2, i):
if n==0:
if x==1:

# using enumerate in a for loop

grocery = [‘bread’, ‘milk’, ‘butter’]
enumerateGrocery = enumerate(grocery)

for item in enumerate(grocery):

for count, item in enumerate(grocery):
print(count, item)

# using zip in a for loop
letters = [‘a’, ‘b’, ‘c’]
numbers = [0, 1, 2]
for l, n in zip(letters, numbers):
print(f’Letter: {l}’)
print(f’Number: {n}’)

dict_one = {‘name’: ‘John’, ‘last_name’: ‘Doe’, ‘job’: ‘Python Consultant’}
dict_two = {‘name’: ‘Jane’, ‘last_name’: ‘Doe’, ‘job’: ‘Community Manager’}
for (k1, v1), (k2, v2) in zip(dict_one.items(), dict_two.items()):
print(k1, ‘->’, v1)
print(k2, ‘->’, v2)

# Lists comprehension [expression for item in list]

# common way to loop
h_letters = []

for letter in ‘human’:


# using list comprehension
h_letters = [ letter for letter in ‘human’ ]
# with if embebed
number_list = [ x for x in range(20) if x % 2 == 0]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Tue Apr 20 13:21:29 2021

@author: robertocabieces

import os
from os import listdir
from os.path import isfile, join

# List the files of a folder

files_path = os.path.join(os.getcwd(), “files_folder_name”)

obsfiles = []
for top_dir, sub_dir, files in os.walk(files_path):
for file in files:
obsfiles.append(os.path.join(top_dir, file))

obsfiles = [f for f in listdir(files_path) if isfile(join(files_path, f))]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Fri Apr 23 08:29:21 2021

@author: robertocabieces

# Functions
def function-name(parameters):

def printer(message):
print(‘Hello ‘ + message)

# Return statement
def sum(a, b):
return a + b

k = sum(10, 20)
print (“Sum is”, k)

# Multiple returns

def conv(x):

if x==1:
return “one”

if x==2:
return “two”

if x==3:
return “three”

if x==4:
return “four”

return “Try it on again”

def fib(n): # write Fibonacci series up to n
“””Print a Fibonacci series up to n.”””
a, b = 0, 1
while a < n:
print(a, end=’ ‘)
a, b = b, a+b

def sum(x, y=10):

return x+y

r = sum(10)
r = sum(5,8)

# Using default arguments adn kewords
def sum_new(x, y=10, boolean = False):

if boolean:

z = x + y


z = x

return z

# Using magic method

def rect(l,b):
”’Computes the area of rectangle Values for length and breadth are passed to the function for computation”’
print (‘Area of rectangle is’, l*b)
print (rect.__doc__)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Fri Apr 23 09:07:41 2021

@author: robertocabieces

# Recursion
# Calcular la suma de 10 números
def addseq(x):
if x == 1:

return 1

return x + addseq(x-1)

def fact(x):
if x == 1:

return 1


return x * fact(x-1)

x = addseq(10)

print (‘The factorial of 5 is’, fact(5))

def cheeseshop(kind, *arguments, **keywords):
print(“– Do you have any”, kind, “?”)
print(“– I’m sorry, we’re all out of”, kind)
for arg in arguments:
print(“-” * 40)
for kw in keywords:
print(kw, “:”, keywords[kw])

cheeseshop(“Limburger”, “It’s very runny, sir.”,
“It’s really very, VERY runny, sir.”,
shopkeeper=”Michael Palin”,
client=”John Cleese”,
sketch=”Cheese Shop Sketch”)

# consejo —> depth = kwargs.pop(‘depth’, [])

# lamda function
# syntaxis

# lambda arguments : expression
# x = lambda a, b, c : a + b + c

def make_incrementor(n):
z = lambda x: x + n
return z

z = make_incrementor(10)

# Functions inside lists
# take second element for sort

def takeSecond(elem):
return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key

# print list
print(‘Sorted list:’, random)


# Anotations

def f(ham: str, eggs: str = ‘eggs’) -> str:
print(“Annotations:”, f.__annotations__)
print(“Arguments:”, ham, eggs)
return ham + ‘ and ‘ + eggs


# Example to illustrate a well documented method, from https://docs.obspy.org/
def array_processing(stream, win_len, win_frac, sll_x, slm_x, sll_y, slm_y,
sl_s, semb_thres, vel_thres, frqlow, frqhigh, stime,
etime, prewhiten, verbose=False, coordsys=’lonlat’,
timestamp=’mlabday’, method=0, store=None):
Method for Seismic-Array-Beamforming/FK-Analysis/Capon

:param stream: Stream object, the trace.stats dict like class must
contain an :class:`~obspy.core.util.attribdict.AttribDict` with
‘latitude’, ‘longitude’ (in degrees) and ‘elevation’ (in km), or ‘x’,
‘y’, ‘elevation’ (in km) items/attributes. See param “coordsys“.
:type win_len: float
:param win_len: Sliding window length in seconds
:type win_frac: float
:param win_frac: Fraction of sliding window to use for step
:type sll_x: float
:param sll_x: slowness x min (lower)
:type slm_x: float
:param slm_x: slowness x max
:type sll_y: float
:param sll_y: slowness y min (lower)
:type slm_y: float
:param slm_y: slowness y max
:type sl_s: float
:param sl_s: slowness step
:type semb_thres: float
:param semb_thres: Threshold for semblance
:type vel_thres: float
:param vel_thres: Threshold for velocity
:type frqlow: float
:param frqlow: lower frequency for fk/capon
:type frqhigh: float
:param frqhigh: higher frequency for fk/capon
:type stime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param stime: Start time of interest
:type etime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param etime: End time of interest
:type prewhiten: int
:param prewhiten: Do prewhitening, values: 1 or 0
:param coordsys: valid values: ‘lonlat’ and ‘xy’, choose which stream
attributes to use for coordinates
:type timestamp: str
:param timestamp: valid values: ‘julsec’ and ‘mlabday’; ‘julsec’ returns
the timestamp in seconds since 1970-01-01T00:00:00, ‘mlabday’
returns the timestamp in days (decimals represent hours, minutes
and seconds) since ‘0001-01-01T00:00:00’ as needed for matplotlib
date plotting (see e.g. matplotlib’s num2date)
:type method: int
:param method: the method to use 0 == bf, 1 == capon
:type store: function
:param store: A custom function which gets called on each iteration. It is
called with the relative power map and the time offset as first and
second arguments and the iteration number as third argument. Useful for
storing or plotting the map for each iteration. For this purpose the
dump function of this module can be used.
:return: :class:`numpy.ndarray` of timestamp, relative relpow, absolute
relpow, backazimuth, slowness

# -*- coding: utf-8 -*-
Created on Tue May 10 08:18:02 2016

@author: R.Cabieces

class rect:
def __init__(self, x, y):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b

def __str__(self):
return ‘Length is %d, Breadth is %d’ % (self.l, self.b)

r = rect(5,8)

print(“Area of rectangle is “, r.rectarea())

# -*- coding: utf-8 -*-
Created on Sat Jun 11 11:14:45 2016

@author: ericgrimson
import random

class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=””):
self.name = newname
def __str__(self):
return “animal:”+str(self.name)+”:”+str(self.age)

class Cat(Animal):

add new functionality with speak()
instance of type Cat can be called with new methods
instance of type Animal throws error if called with new methods

def __init__(self, age):
Animal.__init__(self, age)

def speak(self):

def __str__(self):
return “cat:”+str(self.name)+”:”+str(self.age)

class Rabbit(Animal):
def speak(self):
def __str__(self):
return “rabbit:”+str(self.name)+”:”+str(self.age)

class Person(Animal): # Parent class is Animal

def __init__(self, name, age):

# call Animal constructor
Animal.__init__(self, age)

# call Animal method
Animal.set_name(self, name)
# set new data attribute
self.friends = []

def get_friends(self):
return self.friends

def add_friend(self, fname):
if fname not in self.friends:

def speak(self):

def age_diff(self, other):
# alternate way: diff = self.age – other.age
diff = self.get_age() – other.get_age()
if self.age > other.age:
print(self.name, “is”, diff, “years older than”, other.name)
print(self.name, “is”, -diff, “years younger than”, other.name)

def __str__(self):
return “person:”+str(self.name)+”:”+str(self.age)

class Student(Person):
def __init__(self, name, age, major=None):
Person.__init__(self, name, age)
self.major = major
def change_major(self, major):
self.major = major
def speak(self):
r = random.random()
if r < 0.25:
print(“i have homework”)
elif 0.25 <= r < 0.5:
print(“i need sleep”)
elif 0.5 <= r < 0.75:
print(“i should eat”)
print(“i am watching tv”)
def __str__(self):
return “student:”+str(self.name)+”:”+str(self.age)+”:”+str(self.major)

if __name__ == “__main__”:
jelly = Cat(1)
rober = Rabbit(3)

#jelly = Cat(1)
#tiger = Cat(1)
#bean = Cat(0)
#blob = Animal(1)
#peter = Rabbit(3)
#eric = Person(‘Eric’, 45)
#john = Person(‘John’, 55)
#fred = Student(‘Fred’, 18, ‘Course VI’)

A class method has no self argument and receives a class as its first argument.
By convention, the argument to the class method is called cls.
That is, in a class method, the class on which it is called is passed to it as the first argument.
The class method can also be called directly through the class object without instantiating
the class. A class method is defined using the @classmethod decorator.
A decorator provides a convenient method to insert and modify code in functions or classes.

def f(cls, parm1, parm2, . . .):
body of the method

import math

class book:


def display(cls,x):

def show(self,x):



# You don’t need to create explcitly the object when you use the class method

# You can use the public method
b = book()

Static Methods:

A static method is an ordinary function that is built using the @staticmethod decorator
and that binds its result to a class attribute. The difference between a static method
and a class method is that a static method has no cls parameter. It doesn’t use the self parameter, either.
There is one more difference—the class method is automatically inherited by any child classes,
whereas the static method is not.
Also, the definition of a static method is immutable via inheritance.
A static method can be called on a class or on any instance of a class.

def name (parm. . .) :
body of the method

class rect:

def disp_message():
print(“Length is “, l)


Private attributes and methods __

class rect_private:

def __init__(self, x, y):
self.__l = x
self.__b = y

def __rectarea(self):

return self.__l * self.__b

def diagonal_area(self):

d = math.sqrt((self.__l**2+self.__b**2))
for i in range(4):
i = i + 1

#print(“Area:”, self.rectarea(),”Diagonal”, int(d))



from __future__ import print_function
from obspy import read
import os
import numpy as np

cwd = os.path.join(os.getcwd(),”data”,”*.*”)
output = os.path.join(os.getcwd(),”output”,”data.txt”)
st = read(cwd)

USAGE: export_seismograms_to_ascii.py in_file out_file calibration

for i, tr in enumerate(st):
f = open(“%s_%d” % (output, i), “w”)
f.write(“# STATION %s\n” % (tr.stats.station))
f.write(“# CHANNEL %s\n” % (tr.stats.channel))
f.write(“# START_TIME %s\n” % (str(tr.stats.starttime)))
f.write(“# SAMP_FREQ %f\n” % (tr.stats.sampling_rate))
f.write(“# NDAT %d\n” % (tr.stats.npts))
np.savetxt(f, tr.data , fmt=”%f”)




import numpy as np
import os
from os import listdir
from os.path import isfile, join
import pandas as pd
import matplotlib.pyplot as plt

data_path = os.path.join(os.getcwd(),”output”)

obsfiles = []
data = []
for top_dir, _ , files in os.walk(data_path):

for file in files:
obsfiles.append(os.path.join(top_dir, file))

for file in obsfiles:
if os.path.basename(file) != “.DS_Store”:
df = pd.read_csv(file,sep=” “,comment=’#’, index_col=False)
#time = df[‘time’].values[:].tolist()

fig, axs = plt.subplots(3, 1, figsize=(10, 5),sharex=True)


time = np.arange(len(data[0]))/(50*60)
axs[0].plot(time,data[0], color=”orangered”, linewidth=0.75, label=”PAB.BHZ”)
axs[0].set_xlabel(‘time [min]’)
axs[0].set_ylabel(‘Amplitude counts/s’)

axs[1].plot(time,data[1], linewidth=0.75,label=”PAB.BH1″)
axs[1].set_xlabel(‘time [min]’)
axs[1].set_ylabel(‘Amplitude counts/s’)

axs[2].plot(time, data[2], color=”green”,linewidth=0.75,label=”PAB.BH2″)
axs[2].set_xlabel(‘time [min]’)
axs[2].set_ylabel(‘Amplitude counts/s’)

def onclick(event):
print(‘button=%d, x=%d, y=%d, xdata=%f, ydata=%f’%(event.button, event.x, event.y, event.xdata, event.ydata))

cid = fig.canvas.mpl_connect(‘button_press_event’, onclick)




#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Wed May 12 08:30:45 2021

@author: robertocabieces

import numpy as np
# we need the following package
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# For this example we first create some random input.
# You can use your own dataset by reading in your data first
x = np.random.randn(100)
y = x + np.random.randn(100) + 10

# Insert linear fit

#from scipy import stats
#slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
#line = slope*x+intercept
#we can add some oppacity with alpha (0 to 1)
#plt.plot(x, line, alpha=0.5)

plt.title(‘Example Scatter Plot’)



#create a third dimension, for example temperature
z = np.random.randn(100)*70

#plt.scatter(x,y, cmap=’viridis’, c=z)

#even better to spot the difference:
#change the size according to the third data dimension
#colorbar can be restricted by vmin and vmax
plt.scatter(x, y, cmap=’viridis’, c=z, s=z, vmin=-40, vmax=140)

plt.title(‘Example Scatter Plot’)


#set colorbar axis to customized range


#create a second data set
x_2 = np.random.randn(100)
y_2 = x_2 + np.random.randn(100) + 10
z_2 = np.random.randn(100)*70

#shades of red with z=color itensity
plt.scatter(x, y, cmap=’Reds’, c=z, label=’dataset 1′)

#shades of blue with z=color intensity
plt.scatter(x_2, y_2, cmap=’Blues’, c=z_2, marker =’v’, label=’dataset 2′)


plt.title(‘Difference day and night’)

fig = plt.figure()
ax = fig.add_subplot(111, projection=’3d’)

#colored by the z values
ax.scatter(x, y, z, c=z)

ax.set_xlabel(‘X Label’)
ax.set_ylabel(‘Y Label’)
ax.set_zlabel(‘Z Label’)

plt.title(‘3D scatter plot’)

n = 12
#creates a array ranging from 0 to 11
X = np.arange(n)

#n random number, uniform distribution
Y1 = np.random.uniform(0.5, 1.0, n)
Y2 = np.random.uniform(0.5, 1.0, n)

#set a face and edge color
plt.bar(X, +Y1, facecolor=’#9999ff’)
plt.bar(X, -Y2, facecolor=’#ff9999′)

for x,y in zip(X,Y1):
#shift the values slightly above the bars
plt.text(x+0.1, y+0.05, ‘%.2f’ % y, ha=’center’, va= ‘bottom’)

for x,y in zip(X,Y2):
plt.text(x+0.1, -y-0.05, ‘%.2f’ % y, ha=’center’, va= ‘top’)

plt.xlim(-.5, n)
#remove ticks on x axis

plt.ylim(-1.25, +1.25)
#or fully remove the ticks/labels

plt.title(‘Histogram example’)



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Wed May 12 08:49:14 2021

@author: robertocabieces
#same random data set as before for the scatter plot
#this time with seaborn
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x_2 = np.random.randn(100)
y_2 = x_2 + np.random.randn(100) + 10

#data needs to put into this format
data = pd.DataFrame({“x”: x_2, “y”: y_2})

#scatter plot with distribution along x and y coordinate
#first plot: default
sns.jointplot(x=x_2, y=y_2, data=data)

#but you can also play around with the “kind” option
#second plot: hex + changed color
sns.jointplot(x=x_2, y=y_2, data=data, kind=”reg”, space=0, color=”r”)

#third plot: kde + changed color
sns.jointplot(x=x_2, y=y_2, data=data, kind=”kde”, space=0, color=”g”)




#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Created on Wed May 12 08:58:33 2021

@author: robertocabieces

import seaborn as sns
import matplotlib.pyplot as plt
#Error bar plots


#Load the example tips dataset
tips = sns.load_dataset(“tips”)

#Draw a nested boxplot to show bills by day and sex
sns.boxplot(x=”day”, y=”total_bill”, hue=”sex”, data=tips, palette=”PRGn”)

#This setting removes the borders to minimalize the figure
sns.despine(offset=10, trim=True)


# Heatmaps

# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset(“flights”)
flights = flights_long.pivot(“month”, “year”, “passengers”)

# Draw a heatmap with the numeric values in each cell
f, ax = plt.subplots(figsize=(9, 6))

#main command
sns.heatmap(flights, annot=True, fmt=”d”, linewidths=.5, ax=ax)

# plt.savefig(‘my_figure.png’, dpi=800)

# -*- coding: utf-8 -*-

Created on Wed Feb 10 12:48:53 2021

@author: rcabd

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import xarray as xr
import cartopy.crs as ccrs
import cmocean
import numpy as np

# Open gebco ndc file from (https://download.gebco.net/) and slice desired area.
# etopo = xr.open_dataset(‘C:\\Users\\rcabd\\Documents\\maps_cartopy\\gebco_2020.nc’)
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

etopo = xr.open_dataset(“/Users/robertocabieces/Desktop/Python_Course/Tema5_Utililies/bathymetry/”
# Slice desired coordinates.
etopo = etopo.sel(lon=slice(-12, -4), lat=slice(34, 38))

# Load sliced variables.
lat = etopo.lat
lon = etopo.lon
topo = etopo.elevation

# Create figure.
fig = plt.figure(1, figsize=(10, 8), facecolor=’w’)

# Use Cartopy projection.
ax = plt.axes(projection=ccrs.PlateCarree())
xmin = -12
xmax = -4
ymin = 34
ymax = 38
extent = [xmin, xmax, ymin, ymax]
ax.set_extent(extent, crs=ccrs.PlateCarree())
x, y = np.gradient(topo)
slope = (np.pi / 2) – np.arctan(np.sqrt(x * x + y * y))

# -x here because of pixel orders in the SRTM tile
aspect = np.arctan2(-x, y)

altitude = np.pi / 4.
azimuth = np.pi / 2.

shaded = np.sin(altitude) * np.sin(slope) + np.cos(altitude) * np.cos(slope) * np.cos((azimuth – np.pi / 2) – aspect)

etopo[‘elevation’].data = shaded
sombreado = etopo.elevation
ax.contourf(lon, lat, sombreado, cmap=’Greys’, transform=ccrs.PlateCarree(), latlon=True,
vmin=np.min(shaded), vmax=np.max(shaded), extend=”both”)

bathymetry = xr.open_dataset(“/Users/robertocabieces/Desktop/Python_Course/Tema5_Utililies/bathymetry/”
# Slice desired coordinates.
bathymetry = bathymetry.sel(lon=slice(-12, -4), lat=slice(34, 38))

# Load sliced variables.
lat1 = bathymetry.lat
lon1 = bathymetry.lon
baty = bathymetry.elevation

center = 0
divnorm = mcolors.TwoSlopeNorm(vmin=baty.min(), vcenter=center, vmax=baty.max())

plot = ax.contourf(lon, lat, baty, 100, cmap=cmocean.cm.topo,
transform=ccrs.PlateCarree(), latlon=True, antialiased=True, norm=divnorm,
extend=”both”, alpha=0.75)

# Disable top and right grid line labels.

gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=0.2, color=’gray’, alpha=0.2, linestyle=’-‘)

gl.top_labels = False
gl.left_labels = False
gl.xlines = False
gl.ylines = False
gl.yformatter = LATITUDE_FORMATTER

ticks = np.arange(baty.min(), baty.max(), 1000)
cax = fig.add_axes([0.30, 0.2, 0.4, 0.025])
cb = fig.colorbar(plot, cax=cax, orientation=”horizontal”, ticks=ticks)
cb.set_label(r’Elevation [m]’, fontsize=9, color=’0.2′, labelpad=0)
# Save figure.
#plt.savefig(‘./map_raster.png’, transparent=False, bbox_inches = ‘tight’,
#pad_inches=0, dpi=100)

# -*- coding: utf-8 -*-
Created on Fri Jan 29 11:39:25 2021

@author: rcabd

import cartopy
from matplotlib.transforms import offset_copy
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
import matplotlib.pyplot as plt
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from owslib.wms import WebMapService
from matplotlib.patheffects import Stroke
import cartopy.feature as cfeature
import shapely.geometry as sgeom
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

# catalog aspect #

Evento Fecha Hora Latitud Longitud Profundidad Magnitud Localizacion
roa2021amyn 1/8/2021 01:06.9 37.4247 -3.8886 21 2 Spain
roa2021aonl 1/8/2021 41:55.7 37.038 -5.8677 0 2.6 Spain
roa2021aoop 1/8/2021 17:02.8 37.1833 -3.717 0 2.1 Spain


geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum=’WGS84′))

#request = cimgt.OSM()
request = cimgt.StamenTerrain()
#load data
data = pd.read_csv(‘C:\\Users\\rcabd\\Documents\\granada\\catalogo_mod_new.txt’,sep=’ ‘, skiprows=1, index_col=False)
lat = data[‘Latitud’]
lon = data[‘Longitud’]
depth = data[‘Profundidad’]
mag = data[‘Magnitud’]
mag = np.array(mag)
mag = 0.5*np.exp(mag)

proj = ccrs.PlateCarree()
fig, ax = plt.subplots(1, 1, subplot_kw=dict(projection=proj), figsize=(16, 12))

xmin = -3
xmax = -4.5
ymin = 36.5
ymax = 38
extent = [xmin, xmax, ymin, ymax]
ax.set_extent(extent, crs=ccrs.PlateCarree())

coastline_10m = cartopy.feature.NaturalEarthFeature(‘physical’, ‘coastline’, ’10m’,
edgecolor=’k’, alpha=0.6, linewidth=0.5,
ax.add_image(request, 8)


#geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax)
color_map = plt.cm.get_cmap(‘rainbow’)
reversed_color_map = color_map.reversed()
geodetic_transform = ccrs.PlateCarree()._as_mpl_transform(ax)
text_transform = offset_copy(geodetic_transform, units=’dots’, x=-25)
cs=ax.scatter(lon, lat, s=mag, marker=”o”, c=depth, alpha=0.7,cmap=reversed_color_map,edgecolors=’black’, transform=ccrs.PlateCarree())
cb = fig.colorbar(cs, orientation=’horizontal’, fraction=0.05, extend=’both’, pad=0.05, label =’Depth (km)’)

#Plot Magnitudes
kw = dict(prop=”sizes”, num=5, fmt=”{x:.0f}”, color = “red”, func=lambda s: np.log(s / 0.5))
ax.legend(*cs.legend_elements(**kw),loc=”lower right”, title=”Magnitudes”)

gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=0.2, color=’gray’, alpha=0.2, linestyle=’-‘)

gl.top_labels = False
gl.left_labels = False
gl.xlines = False
gl.ylines = False

gl.yformatter = LATITUDE_FORMATTER